面試刷題偶有記錄

絕命毒師J發表於2020-09-25

1. 在排序陣列中查詢元素的第一個和最後一個位置

給定一個按照升序排列的整數陣列 nums,和一個目標值 target。找出給定目標值在陣列中的開始位置和結束位置。

你的演算法時間複雜度必須是 O(log n) 級別。

如果陣列中不存在目標值,返回 [-1, -1]。

示例:輸入: nums = [5,7,7,8,8,10], target = 8

輸出: [3,4]

​
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int left = searchRangeLeft(nums, target);
        int right = searchRangeRight(nums, target);
        int[] res = {left, right};
        return res;
    }

    private int searchRangeRight(int[] a, int v){
        int l = 0;
        int r = a.length - 1;
        int res = -1;
        while(l <= r){
            int mid = l + ((r-l)>>1);
            if(a[mid] < v){
                l = mid + 1;
            }else if(a[mid] > v){
                r = mid - 1;
            }else{
                res = mid;
                l = mid + 1;
            }
        }
        return res;
    }
    private int searchRangeLeft(int[] a, int v){
        int l = 0;
        int r = a.length - 1;
        int res = -1;
        while(l <= r){
            int mid = l + ((r-l)>>1);
            if(a[mid] > v){
                r = mid - 1;
            }else if(a[mid] < v){
                l = mid + 1;
            }else{
                res = mid;
                r = mid - 1;
            }
        }
        return res;
    }
}

​

上面這個AC過了,下面這個自己寫案例都能過,但是提交顯示,程式碼在下方,求個有緣人幫我看看,謝謝

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int left = searchRangeLeft(nums, target);
        int right = searchRangeRight(nums, target);
        int[] res = {left, right};
        return res;
    }

    public int searchRangeLeft(int[] nums, int target){
        int low = 0;
        int high = nums.length -1;
        int mid;
        while(low<high){
            mid = low+(high-low)/2;
            if(nums[mid] >= target){
                high = mid;
            }else{
                low = mid+1;
            }
        }
        return nums[low]==target?low:-1;
    }

    public int searchRangeRight(int[] nums, int target){
        int low = 0;
        int high = nums.length -1;
        while(low<high){
            int mid = (low+high)/2 + 1;
            if(nums[mid] <= target){
                low = mid;
            }else{
                high = mid-1;
            }
        }
        return nums[low]==target?low:-1;
    }
}

留個坑,後續繼續補

 

相關文章