leetcode----34. Find First and Last Position of Element in Sorted Array

链接:

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

大意:

给定一个有序数组(升序,有重复数字)nums以及一个待查找的数字target,返回target在数组nums中出现的首位置和尾位置组成的数组,如果target在nums中不存在,则返回[-1,-1]。要求时间复杂度为O(logn)。例子:

思路:

先通过二分查找法找到target在nums中的一个位置(若不存在则返回数组[-1,-1]),记为index。之后从index往左找target在nums中出现的首位置,从index往右找target在nums中出现的尾位置。

代码:

 

class Solution {
    public int[] searchRange(int[] nums, int target) {
        if (nums.length == 0 || nums.length == 1 && nums[0] != target)
            return new int[]{-1, -1};
        int[] res = new int[]{-1, -1};
        int s = 0, e = nums.length - 1, index = -1;
        // 二分法查找
        while (s <= e) {
            int mid = (s + e) / 2;
            if (target > nums[mid])
                s = mid + 1;
            else if (target < nums[mid])
                e = mid - 1;
            else {
                index = mid;
                break;
            }
        }
        if (index == -1)
            return res;
        res[0] = res[1] = index;
        while (res[0] - 1 >= 0 && nums[res[0] - 1] == target) {
            res[0]--;
        }
        while (res[1] + 1 <= nums.length - 1 && nums[res[1] + 1] == target) {
            res[1]++;
        }
        return res;
    }
}

结果:

结论:

找到target在nums中的一个位置index时,往左找需要先判断 index - 1位置的值是否为target,如果是target,再将index-1;如果不是target,则跳出循环。往右找也是如此

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值