Search for a Range

来源:互联网 发布:墨子卫星 知乎 编辑:程序博客网 时间:2024/06/06 01:04
-----QUESTION-----

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 value8,
return [3,4].

-----SOLUTION-----

class Solution {public:    vector< int > searchRange(int A[], int n, int target) {        //二分找最左端,再二分找最右端。        result.clear();        binarySearchLeft(A,-1,n,target);        if(result[0]!=-1) binarySearchRight(A,-1,n,target);        return result;    }        void binarySearchLeft(int A[], int start, int end, int target){ //find the first value == target        if (start+1 == end){            if(end >= n || A[end]!=target){                result.push_back(-1);                result.push_back(-1);            }             else result.push_back(end);            return;        }                 int mid = start + ((end-start)>>1);                  if (A[mid] < target)             binarySearchLeft(A, mid, end, target);         else             binarySearchLeft(A, start, mid, target);          }        void binarySearchRight(int A[], int start, int end, int target){ //find the first value == target        if (start+1 == end){             result.push_back(start);              return;        }                      int mid = start + ((end-start)>>1);                  if (A[mid] > target)             binarySearchRight(A, start, mid, target);         else             binarySearchRight(A, mid, end, target);         }private:    vector< int >  result;};

0 0
原创粉丝点击