Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
webVueBlog opened this issue Sep 3, 2022 · 0 comments
Open

Comments

@webVueBlog
Copy link
Owner

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

Description

Difficulty: 中等

Related Topics: 数组, 二分查找

给你一个按照非递减顺序排列的整数数组 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]

提示:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • nums 是一个非递减数组
  • -109 <= target <= 109

Solution

Language: JavaScript

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var searchRange = function(nums, target) {
    let [start, end] = [0, nums.length - 1]

    while (start <= end) {
        const mid = (start + end) >>> 1
        if (nums[mid] === target) {
            [start, end] = [mid, mid]
            break
        }
        nums[mid] > target ? (end = mid - 1) : (start = mid + 1)
    }

    while (nums[start - 1] === target) start --
    while (nums[end + 1] === target) end++

    return start > end ? [-1, -1] : [start, end]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant