题目:
给你一个按照非递减顺序排列的整数数组 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]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array
解法一:
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function(nums, target) {
let hight = nums.length-1,low = 0,mid = Math.floor((nums.length-1)/2),flag = false
while(low<=hight){
if(nums[mid]===target) {
flag = true
break
}
if(nums[0]===target){
mid=0
flag = true
break
}
if(target<nums[mid]){
hight = mid - 1
}else{
low = mid + 1
}
mid = Math.floor((hight + low)/2)
}
if(flag){
hight = mid
low = mid
while(nums[--low]===target){}
while(nums[++hight]===target){}
return [low+1,hight-1]
}
return [-1,-1]
};
这个是我一刷的解法,好像不太符合题意,最坏的时间复杂度为O(n)。还需加油....
解法二:
var searchRange = function(nums, target) {
let leftIndex, rightIndex
let low = 0, hight = nums.length-1, mid
while(low<=hight){
mid = Math.floor((hight+low)/2)
if(nums[mid]>=target){
hight = mid - 1
leftIndex = mid
}else{
low = mid + 1
}
}
low = leftIndex, hight = nums.length - 1
while(low<=hight){
mid = Math.floor((hight+low)/2)
if(nums[mid]<=target){
low = mid + 1
rightIndex = mid
}else{
hight = mid - 1
}
}
if(leftIndex<=rightIndex&&rightIndex<nums.length&&nums[leftIndex]===target&&nums[rightIndex]===target) return [leftIndex,rightIndex]
else return [-1, -1]
};
解法二参考了标准答案对解法一进行了优化,将时间复杂度控制在O(log n);
解法三:
const binarySearch = (nums, target, lower) => {
let left = 0, right = nums.length - 1, ans = nums.length;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (nums[mid] > target || (lower && nums[mid] >= target)) {
right = mid - 1;
ans = mid;
} else {
left = mid + 1;
}
}
return ans;
}
var searchRange = function(nums, target) {
let ans = [-1, -1];
const leftIdx = binarySearch(nums, target, true);
const rightIdx = binarySearch(nums, target, false) - 1;
if (leftIdx <= rightIdx && rightIdx < nums.length && nums[leftIdx] === target && nums[rightIdx] === target) {
ans = [leftIdx, rightIdx];
}
return ans;
};
解法三的巧妙之处在于用一个lower参数来控制查找的元素是在最左或最右位置,如果为true则返回最左位置,否则返回最右位置。