xinyu04

导航

LeetCode 34 Find First and Last Position of Element in Sorted Array lower_bound & upper_bound

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with \(O(\log n)\) runtime complexity.

Solution

使用 \(cpp\) 自带的 \(lower\_bound, upper\_bound\)
以及 \(python\) 手写

点击查看代码
class Solution:

   
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        def left_bound(nums, tgt):
            left = 0
            right = len(nums)

            while left<right:
                mid = int(left + (right - left) / 2)
                if nums[mid]==tgt:
                    right = mid
                elif nums[mid]<tgt:
                    left = mid+1
                elif nums[mid]>tgt:
                    right = mid
                

            if left >= len(nums):
                return -1

            if nums[left]==target:
                return left
            else:
                return -1
        def right_bound(nums, tgt):
            left = 0
            right = len(nums)

            while left<right:
                mid = int(left + (right-left)/2)
                if nums[mid]==tgt:
                    left = mid+1
                elif nums[mid]<tgt:
                    left = mid+1
                elif nums[mid]>tgt:
                    right = mid
            if left-1>=len(nums) or left-1<0:
                return -1
            if nums[left-1]==tgt:
                return left-1
            else:
                return -1 
        
        ans = []
        ans.append(left_bound(nums, target))
        ans.append(right_bound(nums, target))
        return ans

点击查看代码
class Solution {
private:
    map<int,int>mp;
    vector<int> ans;
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int n = nums.size();
        for(int i=0;i<n;i++)mp[nums[i]]++;
        if(mp[target]==0){
            ans.push_back(-1);ans.push_back(-1); return ans;
        }
        // greater or equal to
        int st = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); ans.push_back(st);
        // strictly greater
        int ed = upper_bound(nums.begin(), nums.end(), target) - nums.begin(); ans.push_back(ed-1);
        return ans;
    }
};

posted on 2022-07-28 16:26  Blackzxy  阅读(11)  评论(0编辑  收藏  举报