[leetcode] 34. Search for a Range

来源:互联网 发布:php global用法 编辑:程序博客网 时间:2024/05/21 02:52

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;            }};



0 0