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

该博客介绍了如何在已排序的整数数组中查找目标值的第一个和最后一个位置。使用二分查找方法,如Python的bisect模块和C++的lower_bound及upper_bound函数,可以在O(logn)的时间复杂度内解决此问题。
摘要由CSDN通过智能技术生成

题目:

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

难度:中等 🌟


给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

如果数组中不存在目标值 target,返回 [-1, -1]

进阶:

  • 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?

示例 1:

输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]

示例 2:

输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]

示例 3:

输入:nums = [], target = 0
输出:[-1,-1]

题解:

p y t h o n 3 python3 python3 内置 b i s e c t bisect bisect 模块

  • 首先判断target是否在nums中,如果不在那么就返回[-1,-1]
  • targetnums 中,那么通过 bisect.bisect_left 可以在 nums 中找到出现 target 最左边的索引
  • bisect.bisect_right 找在 nums 中出现 target 最右边的索引 (注意 ,返回值为数组的索引值+1)

c + + c++ c++ l o w e r _ b o u n d lower\_bound lower_bound u p p e r _ b o u n d upper\_bound upper_bound 函数

  • lower_bound 是找到有序数组中,第一个满足 nums[i]>=ei

  • upper_bound 是找到有序数组中,第一个满足 nums[i]>ei 。其中 target 是待查找的元素。

  • 当两个函数返回值一样的时候 ,说明 target不存在

python3

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        if target not in nums:
            return [-1,-1]

        left = bisect.bisect_left(nums,target)
        right = bisect.bisect_right(nums,target) - 1

        return [left,right]

c++

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {

        int low = lower_bound(nums.begin(),nums.end(),target)-nums.begin();
        int high = upper_bound(nums.begin(),nums.end(),target)-nums.begin();
        if(low==high) return vector<int>{-1,-1};
        else return vector<int>{low,high-1};
    }
};

复杂度分析:

时间复杂度: O ( l o g n ) O(logn) O(logn) ,其中 n n n 为数组的长度。二分查找的时间复杂度为 O ( l o g n ) O(logn) O(logn) ,一共会执行两次,因此总时间复杂度为 O ( l o g n ) O(logn) O(logn)

空间复杂度: O ( 1 ) O(1) O(1) 。只需要常数空间存放若干变量。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值