二分查找-有序数组出现的第一个下标和最后一个下标

这是在面试的时候写的一道题,不过当时由于把递归函数recurse里面的 <target_loc= =-1> 写成了 <target= =-1> 导致出现断错误,面完后一下子就找到bug,哎,可惜了

#include <iostream>
#include <vector>
#include <stack>
#include <map>
#include <string>
#include <math.h>
#include <cstdlib>
#include<cstdio>
#include<cstring>
#include<algorithm>


using namespace std;

// To execute C++, please define "int main()"

// The TestCase is shown below
// Input : 1 2
// Output : 3

//[1,2,2,2,2,3,3,4,4,5,5,6,6,7,7,8]


int func(vector<int> arr, 
         const int target,
        int left,int right){
    while(left<right){
        int mid = (left+right)/2;
        if(arr[mid]==target)
            return mid;
        else if(arr[mid]<target)
            left = mid+1;
        else
            right = mid-1;
    }
    return -1;
}


void recurse(vector<int> arr, int target,int left, int right,vector<int> &res){
    if(left<right){
        int target_loc = func(arr,target,left,right);
        if(target_loc==-1)
            return;
        res.push_back(target_loc);
        recurse(arr,target,left,target_loc-1,res);
        recurse(arr,target,target_loc+1,right,res);
    }
}


int main(){
    vector<int> arr={1,2,2,2,2,3,3,4,4,5,5,6,6,7,7,8};
    vector<int> res;
    recurse(arr,2,0,arr.size()-1,res);
    
    cout<<res[res.size()-2]<<" "<<res[res.size()-1]<<endl;
    
    return 0;
}
posted @ 2020-09-19 10:42  real-zhouyc  阅读(367)  评论(0编辑  收藏  举报