74-Search for a Range

来源:互联网 发布:java 批量导入对象 编辑:程序博客网 时间:2024/05/05 11:44
  1. Search for a Range My Submissions QuestionEditorial Solution
    Total Accepted: 83626 Total Submissions: 285587 Difficulty: Medium
    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].

题意:在有序数组中找到目标元素并返回其对应的索引区间
思路:用二分查找找到中间元素位置,并向两边扩展

时间复杂度:O(logn+k)k
空间复杂度:O(1)

class Solution {public:    vector<int> searchRange(vector<int>& nums, int target) {        int n = nums.size();        int beg = 0,end = n-1;        int mid;        while(beg<=end){  //二分查找目标元素             mid = (beg+end)/2;            if(nums[mid]>target)end = mid-1;            else if(nums[mid]<target)beg = mid+1;            else break;        }        vector<int> res(2,-1);        cout<<"mid:"<<mid<<" "<<nums[mid]<<endl;        if(nums[mid]==target){    //找到了             beg =0,end = n-1;            int fir=mid,sec=mid;            while(sec<=end&&nums[sec]==target)++sec;  //向右边扩展             while(fir>=0&&nums[fir]==target)--fir;    //向左边扩展             res[0]=fir+1;res[1]=sec-1;                //确定最终位置         }        return res;                      }};
0 0