Appearance
34. 在排序数组中查找元素的第一个和最后一个位置
给你一个按照非递减顺序排列的整数数组 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
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array
javascript
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function (nums, target) {
let start = (end = -1),
left = 0,
right = nums.length - 1
while (left <= right) {
const mid = Math.floor((left + right) / 2)
if (nums[mid] === target) {
let leftMid = mid - 1
while (leftMid >= left && nums[leftMid] === target) leftMid--
start = leftMid + 1
let rightMid = mid + 1
while (rightMid < nums.length && nums[rightMid] === target) rightMid++
end = rightMid - 1
break
} else if (nums[mid] < target) {
left = mid + 1
} else {
right = mid - 1
}
}
return [start, end]
}
var searchRange = function (nums, target) {
return [nums.indexOf(target), nums.lastIndexOf(target)]
}
console.log(searchRange([5, 7, 7, 8, 8, 10], 5))
console.log(searchRange([5, 7, 7, 8, 8, 10], 7))
console.log(searchRange([5, 7, 7, 8, 8, 10], 8))
console.log(searchRange([5, 7, 7, 8, 8, 10], 10))
console.log(searchRange([5, 7, 7, 8, 8, 10], 6))
console.log(searchRange([], 0))