LeetCode 之 Search for a Range

来源:互联网 发布:户外轨迹软件 编辑:程序博客网 时间:2024/03/29 20:55

原题:

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].

看到这个题就知道是二分查找,其实非常简单,但是对边界的处理还是比较麻烦的。。。。

1首先用一个递归来进行,判断start是否比end大,若大于则return(要注意不是>=,因为在等于的情况时,还没有判断这个A[start](或A[end]), 因此在等于的时候会继续进行循环 );

2若中间值不等于target,就分别查找左一半和右一半数组

代码如下(68 ms):

class Solution {public:    vector<int> searchRange(int A[], int n, int target) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        vector<int> result;        result.push_back(-1);        result.push_back(-1);        //把result传下去,方便返回最后结果        search(A,0,n-1, target , result);        return result;    }        void search(int A[] , int start , int end , int target , vector<int>&result){              //返回        if(start > end){            return;        }               if(A[(start+end)/2] == target){            //中间的值和target相等,向前找最小的index放在result[0]中            for(int i = (start+end)/2 ; i>=0 ;i--){                if(A[i]==target){                    result[0]=i;                }                else{                    break;                }            }            //中间的值和target相等,向前找最大的index放在result[1]中            for(int i = (start+end)/2 ; i<= end ;i++){                if(A[i]==target){                    result[1]=i;                }                else{                    break;                }            }            return;        }                        //找左边的        else if(A[(start+end)/2] > target ) search( A, start ,  (start+end)/2 -1 , target , result);        //找右边的        else  search( A, (start+end)/2 +1 , end  , target ,result);    }};