给定一个按照升序排列的整数数组 nums
,和一个目标值 target
。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]
。
示例 1:
输入: nums = [5,7,7,8,8,10]
, target = 8
输出: [3,4]
示例 2:
输入: nums = [5,7,7,8,8,10]
, target = 6
输出: [-1,-1]
题目标签:Array / Binary Search
题目链接:LeetCode / LeetCode中国
考查二分法及其变体。
二分法比较简单,然而,并不容易写对。主要是下标越界、死循环、是否取等号、+1 -1、变left还是right等问题。。
Language | Runtime | Memory |
---|---|---|
java | 0 ms | 44.4 MB |
class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums.length == 0) return new int[]{-1, -1};
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + right >> 1;
if (nums[mid] >= target) right = mid;
else left = mid + 1;
}
if (nums[left] != target) return new int[]{-1, -1};
int st = left;
left = st; right = nums.length - 1;
while (left < right) {
int mid = left + right + 1 >> 1;
if (nums[mid] <= target) left = mid;
else right = mid - 1;
}
return new int[]{st, left};
}
}
Language | Runtime | Memory |
---|---|---|
cpp | 12 ms | N/A |
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while(left <= right){
int mid = (left + right) / 2;
if(nums.at(mid) == target){
int lleft = left, lright = right;
while(lleft <= lright){
int lmid = (lleft + lright) / 2;
if(nums.at(lmid) >= target){
lright = lmid - 1;
}else{
lleft = lmid + 1;
}
}
int rleft = left, rright = right;
while(rleft <= rright){
int rmid = (rleft + rright) / 2;
if(nums.at(rmid) > target){
rright = rmid - 1;
}else{
rleft = rmid + 1;
}
}
return vector<int>{lleft, rright};
}else if(nums.at(mid) > target){
right = mid - 1;
}else{
left = mid + 1;
}
}
return vector<int>{-1, -1};
}
};