题目:
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]。
解法:
快速找出左右边界
// 解法1
var searchRange = function(nums, target) {
let res = [-1, -1],
len = nums.length,
left = 0,
right = len - 1;
// 找出右边界
while(left <= right){
let mid = left + Math.floor((right - left)/2)
if(nums[mid] === target && (mid === len -1 || nums[mid + 1] > target)){
res[1] = mid
break;
}
if(nums[mid] <= target){
left = mid + 1
}else{
right = mid - 1
}
}
// 找出左边界
left = 0
while(left <= right){
let mid = left + Math.floor((right - left)/2)
if(nums[mid] === target && (mid === 0 || nums[mid - 1] < target)){
res[0] = mid
break;
}
if(nums[mid] >= target){
right = mid - 1
}else{
left = mid + 1
}
}
return (res[0] == -1 && res[1] == -1) ? [-1, -1] : res
};
// 解法2
var searchRange2 = function(nums, target) {
const findIndex = (arr, target, position = 'first') => {
let minIndex = 0;
let maxIndex = arr.length - 1;
let midIndex, midValue;
while (minIndex <= maxIndex) {
midIndex = ~~((maxIndex + minIndex) / 2); // Math.floor 即 ~~
midValue = arr[midIndex];
if (midValue === target) {
if (position === 'first' && arr[midIndex - 1] === target) {
maxIndex = midIndex - 1;
} else if (position === 'last' && arr[midIndex + 1] === target) {
minIndex = midIndex + 1;
} else {
return midIndex;
}
} else if (midValue > target) {
maxIndex = midIndex - 1;
} else if (midValue < target) {
minIndex = midIndex + 1;
}
}
return -1;
};
return [findIndex(nums, target, 'first'), findIndex(nums, target, 'last')];
};