题目描述
给定一个按照升序排列的整数数组 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
个人解法
Javascript
/*
* @lc app=leetcode.cn id=34 lang=javascript
*
* [34] 在排序数组中查找元素的第一个和最后一个位置
*/
// @lc code=start
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function (nums, target) {
if (!nums || !nums.length) return [-1, -1];
let left = -1;
let leftFlag = false;
let right = nums.length;
let rightFlag = false;
while (left < right) {
if (!leftFlag && nums[++left] === target) {
leftFlag = true;;
}
if (!rightFlag && nums[--right] === target) {
rightFlag = true;
}
if (leftFlag && rightFlag) {
break;
}
}
return [leftFlag ? left : -1, rightFlag ? right : -1];
};
Java(二分查找)
class Solution {
public int[] searchRange(int[] nums, int target) {
int n1, n2;
int[] result = new int[2];
if(nums.length==0){
int[] r = new int[]{-1,-1};
return r;
}
n1=search(nums, target);
if (nums[n1]!=target){
n1=-1;
}
n2=search(nums, target+1);
if(n1!=-1&&nums[n2]>target){
n2-=1;
}else if(n1==-1){
n2=-1;
}
result[0]=n1;
result[1]=n2;
return result;
}
public int search(int[] nums, int target){
int left = 0, len = nums.length, right = len - 1, mid;
while (left < right) {
//5778810 0 0
mid = (left + right) / 2;
if (target <= nums[mid]) {
right=mid;
} else {
left = mid + 1;
}
}
return left;
}
}
其他解法
Java
Javascript
二分查早是最优的
改进的二分法
//nums = [5,7,7,8,8,10], target = 8
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;
};