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

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

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值