[leetcode] Search for a Range

来源:互联网 发布:在淘宝怎么打开淘口令 编辑:程序博客网 时间:2024/06/06 01:06

From : https://leetcode.com/problems/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].

Hide Tags
 Array Binary Search
Hide Similar Problems
 (M) Search Insert Position

Solution : 

class Solution {public:    vector<int> searchRange(vector<int>& nums, int target) {        int start=0, end=nums.size()-1;        vector<int> ans(2);        ans[0]=ans[1]=-1;        while(start <= end) {            int mid = (start+end)>>1;            if(nums[mid] == target) {                for(int i=mid; i>=start; i--) {                    if(nums[i] == target) {                        ans[0] = i;                    }                }                for(int i=mid; i<=end; i++) {                    if(nums[i] == target) {                        ans[1] = i;                    }                }                break;            }            if(nums[mid] > target) {                end = mid-1;            } else {                start = mid+1;            }        }        return ans;    }};


0 0
原创粉丝点击