天天看點

[leetcode] 34. Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return 

[-1, -1]

.

For example,

Given 

[5, 7, 7, 8, 8, 10]

 and target value 8,

return 

[3, 4]

.

Subscribe to see which companies asked this question

解法一:

思路就是先找從左邊數第一個等于target的,再找從右邊數第一個等于target的。當然如果從左開始找不到target,傳回[-1,-1]。

不過二分法裡面具體細節還要慢慢體會。

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int left = 0, right = nums.size()-1;
        vector<int> res(2,-1);
        
        while(left<right){
            int mid = (left+right)/2;
            if (nums[mid]<target) left = mid + 1;
            else right = mid;
        }
        if(nums[left]!=target) return res;
        res[0] = left;
        
        right = nums.size();
        while(left<right){
            int mid = (left+right)/2;
            if(nums[mid]>target) right = mid;
            else left = mid+1;
        }
        res[1] = left-1;
        return res;
        
    }
};