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

题目描述

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

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

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

解题思路:

java 复制代码
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] res = new int[]{-1,-1};
        int left = 0;
        int right = nums.length-1;
        while(left <= right){
            int temp = (left + right) >> 1;
            if(nums[temp] > target){
                right = temp - 1;
            }else if(nums[temp] < target){
                left = temp + 1;
            }else{
                left = temp;
                right = temp;
                while((right <nums.length-1)&&(nums[right] == nums[right+1])){
                    right++;
                }
                while((left > 0)&&(nums[left] == nums[left-1])){
                    left--;
                }
                res[0] = left;
                res[1] = right;
            }

        }
        return res;
    }
}

这是最朴素的思想,二分查找,如果找到了再往两边拓展,处理边界条件,只可惜超时了。

需要对二分法再进行二分查找。

官方题解:

java 复制代码
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int leftIdx = binarySearch(nums, target, true);
        int rightIdx = binarySearch(nums, target, false) - 1;
        if (leftIdx <= rightIdx && rightIdx < nums.length && nums[leftIdx] == target && nums[rightIdx] == target) {
            return new int[]{leftIdx, rightIdx};
        } 
        return new int[]{-1, -1};
    }

    public int binarySearch(int[] nums, int target, boolean lower) {
        int left = 0, right = nums.length - 1, ans = nums.length;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] > target || (lower && nums[mid] >= target)) {
                right = mid - 1;
                ans = mid;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }
}
相关推荐
IronMurphy7 小时前
【算法四十三】279. 完全平方数
算法
墨染天姬7 小时前
【AI】Hermes的GEPA算法
人工智能·算法
papership7 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_796826527 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
山甫aa7 小时前
差分数组 ----- 从零开始的数据结构
数据结构
早日退休!!!7 小时前
《数据结构选型指南》笔记
数据结构·数据库·oracle
Beginner x_u8 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
丑八怪大丑8 小时前
Java数据结构与集合源码
数据结构
_深海凉_11 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
踩坑记录12 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode