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

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

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if(nums.empty()) return vector<int>{-1, -1};
        int left = left_bound(nums, target);
        if(left == -1) return {-1,-1};
        int right = right_bound(nums, target);
        return vector<int>{left, right};
    }
    int left_bound(vector<int>& nums, int target){
        int left = 0, right = nums.size() - 1;
        int mid;
        while(left <= right){
            mid = left + (right - left) / 2;
            if(nums[mid] == target){
                right = mid - 1;
            }else if(nums[mid] < target){
                left = mid + 1;
            }else if(nums[mid] > target){
                right = mid - 1;
            }
        }
        if(left >= nums.size() || nums[left] != target){
            return -1;
        }
        return left;
    }
    int right_bound(vector<int>& nums, int target){
        int left = 0, right = nums.size() - 1;
        int mid;
        while(left <= right){
            mid = left + (right - left) / 2;
            if(nums[mid] == target){
                left = mid + 1;
            }else if(nums[mid] < target){
                left = mid + 1;
            }else if(nums[mid] > target){
                right = mid - 1;
            }
        }
        if(right < 0 || nums[right] != target){
            return -1;
        }
        return right;
    }
};
class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        n = len(nums)
        if n == 0:
            return [-1, -1]

        def find_left(target):
            l,r = 0,n-1
            while l <= r:
                mid = (r-l)//2 + l
                if nums[mid] < target:
                    l = mid + 1
                else:
                    r = mid-1
            if l > n-1 or nums[l] != target:
                return -1
            return l
        
        def find_right(target):
            l,r = 0,n-1
            while l <= r:
                mid = (r-l)//2 + l
                if nums[mid] <= target:
                    l = mid + 1
                else:
                    r = mid - 1
            if r < 0 or nums[r] != target:
                return -1
            return r

        return [find_left(target), find_right(target)]

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...