​LeetCode刷题实战34:在排序数组中查找元素的第一个和最后一个位置

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做在排序数组中查找元素的第一个和最后一个位置,我们先来看题面:

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

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

Your algorithm's runtime complexity must be in the order of O(log n).

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

题意

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

你的算法时间复杂度必须是 O(log n) 级别。

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

样例


示例 1:

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

示例 2:

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

题解

思路1:手动二分法!

这里提供两种方法,一种容易理解,一种万能公式!

版本1:是指在二分法进行时,就判读是否有等于target的,但是找到的target不知道是最左边的数还是最右边的数,所以,通过找到这个数再找出相应的边界值.

版本2:是指二分法执行完毕,返回target在最左边的位置,在求出另一个边界!

关于详细说明,请看这篇[二分搜索](二分查找有几种写法?它们的区别是什么?- Jason Li的回答 - 知乎
https://www.zhihu.com/question/36132386/answer/530313852),读完之后,可以加深二分搜索的理解!

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] res = {-1, -1};
        int n = nums.length;
        if (n == 0) return res;
        int left = 0;
        int right = n-1;
        while (left <= right){
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                left = mid;
                right = mid;
                while (left > 0 && nums[left] == nums[left-1]) left--;
                while (right < n - 1 && nums[right] == nums[right+1]) right++;
                res[0] = left;
                res[1] = right;
                return res;
            }
            else if (nums[mid] > target) right = mid - 1;
            else left = mid + 1;
        }
        return res;
        
    }
}

思路2:库函数

python 的 bisect库

简要介绍一下,

bisect.bisect_left(a,x,lo=0,hi=len(a))a中找x最左边数的索引,如果找不到就返回插入的索引.

bisect.bisect(a, x, lo=0, hi=len(a)) 找最右边的!

思路3:

分而治之,参考链接:https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/discuss/14707/9-11-lines-O(log-n)

当然上面的时间复杂度都是:O(logn)

本文有点参考于

https://www.cnblogs.com/powercai/p/10826397.html

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。

上期推文:

LeetCode1-20题汇总,速度收藏!

LeetCode刷题实战21:合并两个有序链表

LeetCode刷题实战23:合并K个升序链表

LeetCode刷题实战24:两两交换链表中的节点

LeetCode刷题实战25:K 个一组翻转链表

LeetCode刷题实战26:删除排序数组中的重复项

LeetCode刷题实战27:移除元素

LeetCode刷题实战28:实现 strStr()

LeetCode刷题实战29:两数相除

LeetCode刷题实战30:串联所有单词的子串

LeetCode刷题实战31:下一个排列

LeetCode刷题实战32:最长有效括号

LeetCode刷题实战33:搜索旋转排序数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程IT圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值