[leetcode]034-Find First and Last Position of Element in Sorted Array[二分查找]

1. 原题

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

2. 思路

题意:给出一个有序序列和一个目标值,返回目标值下标的最小和最大值。

时间复杂度要求O(logn),显然要用二分查找。

存在多个重复值,利用二分法分别得到最小和最大索引即可。

3. 源码

class Solution:
    #binary search, return value index
    def getIndex(self, nums: List[int], x: int, left: int, right: int):
        if left > right:
            return -1
        mid = (left + right) // 2
        if nums[mid] < x:
            return self.getIndex(nums, x, mid+1, right)
        elif nums[mid] > x:
            return self.getIndex(nums, x, left, mid-1)
        else:
            return mid
    
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        re = []
        mid = self.getIndex(nums, target, 0, len(nums)-1)
        if mid < 0:
            return [-1, -1]
        else:
            left, right = mid, mid
            while (left > -1): #find the lowest index
                tmp = self.getIndex(nums, target, 0, left-1)
                if tmp > -1:
                    left = tmp
                else:
                    break;
            while (right > -1): #finde the highest index
                tmp = self.getIndex(nums, target, right+1, len(nums)-1)
                if tmp > -1:
                    right = tmp
                else:
                    break;
            re.append(left)   
            re.append(right)
            return re

 

### LeetCode Problem 34: Find First and Last Position of Element in Sorted Array In this problem, given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given target value. If the target is not found in the array, return `[-1, -1]`. The efficient approach involves using binary search twice—once to find the first occurrence of the target and once to find the last occurrence. #### Binary Search Implementation for Finding Positions To locate the positions efficiently: - **Finding the Leftmost Index**: Modify standard binary search so that when encountering the target element, continue searching on the left side until reaching the start. - **Finding the Rightmost Index**: Similarly modify binary search but ensure continued searches occur towards the right whenever finding the target. This ensures logarithmic time complexity O(log n), which significantly improves performance over linear scans especially within large datasets[^1]. ```cpp class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { if (nums.empty()) return {-1, -1}; auto lower = std::lower_bound(nums.begin(), nums.end(), target); if (lower == nums.end() || *lower != target) return {-1, -1}; auto upper = std::upper_bound(lower, nums.end(), target); return {(int)(lower - nums.begin()), (int)(upper - nums.begin()) - 1}; } }; ``` Here, C++ STL functions like `std::lower_bound()` and `std::upper_bound()` are utilized effectively for determining boundaries around elements matching our criteria without manually coding out full binary searches from scratch.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值