Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
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]
方法一:二分法查找
先用二分法寻找target,若未找到则直接返回[-1,-1],找到则将左边界和右边界均设为该值。然后在[0,左边界]中用二分法刷新左边界,在[右边界, nums.size()-1]中刷新右边界。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int len = nums.size(),res_L,res_R;
vector<int> res;
if (len<1 || target<nums[0] || target > nums[len - 1]) {
return vector<int>(2, -1);
}
int first_find = Binary_search(nums, 0, len - 1, target);
if (first_find == -1) {
return vector<int>{-1, -1};
}
else {
res_L = first_find;
res_R = first_find;
}
while (Binary_search(nums, 0, res_L-1, target) != -1) {
res_L = Binary_search(nums, 0, res_L-1, target);
}
while (Binary_search(nums, res_R+1 , len-1 , target) != -1) {
res_R = Binary_search(nums, res_R+1, len - 1, target);
}
res.push_back(res_L);
res.push_back(res_R);
return res;
}
int Binary_search(vector<int> &nums, int left, int right, const int &target) {
int res = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
res = mid;
break;
}
else if (nums[mid] > target) {
right = mid - 1;
continue;
}
else {
left = mid + 1;
continue;
}
}
return res;
}
};
方法二:对二分法查找进行修改
为二分法查找设置一个bool型的参数,当传入的该参数为ture时进行左边界的查找,为false时进行右边界的查找。
查找左边界时,如果nums[mid] > = target, 则令hi = mid;否则令lo = mid+1;当lo==hi时退出循环。左边界的值即为返回值。
查找右边界时,如果nums[mid] > target, 则令hi = mid;否则令lo = mid+1;当lo==hi时退出循环。右边界值即为返回值-1。
左边界查找过程如下:
右边界搜索过程如下:
JAVA代码如下:
class Solution {
// returns leftmost (or rightmost) index at which `target` should be
// inserted in sorted array `nums` via binary search.
private int extremeInsertionIndex(int[] nums, int target, boolean left) {
int lo = 0;
int hi = nums.length;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (nums[mid] > target || (left && target == nums[mid])) {
hi = mid;
}
else {
lo = mid+1;
}
}
return lo;
}
public int[] searchRange(int[] nums, int target) {
int[] targetRange = {-1, -1};
int leftIdx = extremeInsertionIndex(nums, target, true);
// assert that `leftIdx` is within the array bounds and that `target`
// is actually in `nums`.
if (leftIdx == nums.length || nums[leftIdx] != target) {
return targetRange;
}
targetRange[0] = leftIdx;
targetRange[1] = extremeInsertionIndex(nums, target, false)-1;
return targetRange;
}
}