leetcode-34. 在排序数组中查找元素的第一个和最后一个位置_编程题目

 

 

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res;
        int left = lcoateleft(nums,0,nums.size()-1,target);
        int right = lcoateright(nums,0,nums.size()-1,target);
        res.push_back(left);
        res.push_back(right);
        return res;
    }
    int lcoateleft(vector<int> nums,int left, int right, int target){
        int res = -1;
        while(left<=right){
            cout<<"flag1:"<<left<<" "<<right<<endl;
            //cout<<"left: "<<left<<" "<<right<<end;
            int mid = (left+right)/2;
            if(target>nums[mid]) 
                left = mid+1;
            else if(target<nums[mid]) 
                right =mid-1;
            else {
                if((mid-1)<0||(mid-1)>=0&&nums[mid-1]!=target){
                    res = mid;
                    return res;
                }
                    
                else 
                    right = mid-1;
            }
        }
        return res;
    }

    
    int lcoateright(vector<int> nums,int left, int right, int target){
        int res = -1;

        while(left<=right){
            cout<<"flag2: "<<left<<" "<<right<<endl;
           // cout<<"flag2:"<<left<<" "<<right<<end;
            int mid = (left+right)/2;
            if(target>nums[mid]) 
                left = mid+1;
            else if(target<nums[mid]) 
                right =mid-1;
            else {
                /* else 的前提条件是nums[mid]==target
                然后(mid+1)>=nums.size()说明到末尾了,找到右边界了
                或者 没到末尾,但是nums[mid+1]!=target此时也找到右边界了
                */
                if((mid+1)>=nums.size()||(mid+1)<nums.size()&&nums[mid+1]!=target){
                    res = mid;
                    return res;
                }        
                else 
                    left = mid+1;
            }
        }
        //lcoateleft(nums,left,right,target);
        return res;

    }
};