LeetCode - Find First and Last Position of Element in Sorted Array / Search for a Range

解法一  one Binary Search

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if(nums.empty()) return {-1,-1};
        int n = nums.size();
        int l=0,r=n;
        while(l<r){
            int mid = l+(r-l)/2;
            if(target>nums[mid]) l=mid+1;
            else r=mid;
        }
        if(r==n || nums[r]!=target) return {-1,-1};
        int i;
        for(i=r;i<n;i++){
            if(nums[i]!=target) break;
        }
        return {r, i-1};
    }
};

解法二  two Binary Search

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if(nums.empty()) return {-1,-1};
        int n = nums.size();
        int l=0,r=n;
        while(l<r){
            int mid = l+(r-l)/2;
            if(target>nums[mid]) l=mid+1;
            else r=mid;
        }
        if(r==n || nums[r]!=target) return {-1,-1};
        l=r;
        int r2=n;
        while(l<r2){
            int mid = l+(r2-l)/2;
            if(target>=nums[mid]) l=mid+1;
            else r2=mid;
        }
        return {r,r2-1};
    }
};

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/83931830