LeetCode hot100-65-N

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

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

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

你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。

这题我的大体思路就是二分法找到目标值的位置,然后左右找最左和最右的下标。第二步写不对啊,看了下别人的。最后自己写出来的代码大概是这样

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int result[] = new int[]{-1, -1};

        int pos = searchInsert(nums, target);
        if (pos == -1) {
            return result;
        }
        
        int l = pos;
        int r = pos;
        result[0] = pos;
        result[1] = pos;
        while (l > 0 && nums[--l] == target) {
             result[0] = l;   
        }
        while (r < nums.length - 1 && nums[++r] == target) {
             result[1] = r; 
        }
        return result;

    }

    public int searchInsert(int[] nums, int target) {
        int l = 0;
        int r = nums.length - 1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }

        }
        return -1;

    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值