美文网首页
34. 在排序数组中查找元素的第一个和最后一个位置

34. 在排序数组中查找元素的第一个和最后一个位置

作者: const_qiu | 来源:发表于2020-09-02 14:00 被阅读0次

https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
     //左闭右开
    
    int length = nums.size();
    if(length == 0) return {-1,-1} ;
    vector<int> res;
    //搜索左位置
   
    int left = 0;
    int right= length-1;
    // left取值[0,length]
    
    while(left<=right){
        
        int mid = left +(right-left)/2;
        if(target == nums[mid]){
            
            right = mid-1;
        }
        else if(target > nums[mid]){
            
            
            left = mid+1;
        }
        else{
            
            right = mid-1;
        }
        
    }
        
    //数组越界检查
        int res1 = 0;
        if(left == length || nums[left] != target ) res1 = -1;
        else{
             res1 = left ;
        }
    if(res1 == -1) return {-1,-1} ;
    res.push_back(res1);
    //搜索右位置
   
     left = 0;
     right= length-1;
    
    while(left<=right){
        
        int mid = left +(right-left)/2;
        if(target == nums[mid]){
            
            left = mid+1;
        }
        else if(target > nums[mid]){
            
            
            left = mid+1;
        }
        else{
            
            right = mid -1;
        }
        
    }    
    int res2 = 0;
    // 检查越界 ,right[-1,length-1]
    if(right == -1 || nums[right] != target) res2 =-1;
        
    else{
         res2 = right;
    }
   
    res.push_back(res2);
        
    return res;
    }
};

相关文章

网友评论

      本文标题:34. 在排序数组中查找元素的第一个和最后一个位置

      本文链接:https://www.haomeiwen.com/subject/wvdjsktx.html