leetcode34

/*简单二分题目 在每次二分决策的时候对应控制选择左区间或者右区间即可*/
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
            int len = nums.size();
            int left , right , mid;
            int first , last;
            vector<int> ans;
            if(len == 0){
                 ans.push_back(-1);  
                 ans.push_back(-1); 
                 return ans;  
            }
            /*first位置*/
            left = 0;
            right = len - 1;
            while(left < right){
                 mid = (left + right)/2;
                 if(nums[mid] >= target)      right = mid;
                 else if(nums[mid] <  target) left = mid + 1;           
            }
            if(nums[left] != target) first = -1;
            else                     first = left;
            ans.push_back(first);
            
            /*计算last位置*/
            left = 0;
            right = len - 1;
            while(left  < right){
                 mid = (left + right)/2 + 1;
                 if(nums[mid] > target)        right = mid - 1;
                 else if(nums[mid] <=  target) left = mid;           
            }

            if(first == -1)  last = -1;
            else             last = left;
            ans.push_back(last);
            return ans;
    }
};

 

posted on 2020-10-04 15:22  在苏州的城边  阅读(127)  评论(0编辑  收藏  举报

导航