题目描述
Given an array of integers nums
sorted in non-decreasing order, find the starting and ending position of a given target
value.
If target
is not found in the array, return [-1, -1]
.
You must write an algorithm with O(log n)
runtime complexity.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
Example 3:
Input: nums = [], target = 0 Output: [-1,-1]
Constraints:
0 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
nums
is a non-decreasing array.-10^9 <= target <= 10^9
解题思路
【C++】
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if (nums.empty()) {return vector<int> {-1, -1};}
int left = bound(nums, target, true);
if (left == nums.size() || nums[left] != target) {return vector<int> {-1, -1};}
int right = bound(nums, target, false) - 1;
return vector<int> {left, right};
}
int bound(vector<int>& nums, int target, bool left) {
int l = 0, r = nums.size(), mid;
while (l < r) {
mid = (l + r) / 2;
if (nums[mid] > target || (left && nums[mid] == target)) {r = mid;}
else {l = mid + 1;}
}
return l;
}
};
【Java】
class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums.length <= 0) {return new int[] {-1, -1};}
int left = bound(nums, target, true);
if (left == nums.length || nums[left] != target) {return new int[] {-1, -1};}
int right = bound(nums, target, false) - 1;
return new int[] {left, right};
}
int bound(int[] nums, int target, boolean left) {
int l = 0, r = nums.length, mid;
while (l < r) {
mid = (l + r) / 2;
if (nums[mid] > target || (left && nums[mid] == target)) {r = mid;}
else {l = mid + 1;}
}
return l;
}
}