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]
思路:binary search标准模板走起;
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = {-1,-1};
if(nums == null || nums.length == 0) {
return res;
}
res[0] = findFirstPosition(nums, target, 0, nums.length - 1);
res[1] = findLastPosition(nums, target, 0, nums.length - 1);
return res;
}
private int findFirstPosition(int[] nums, int target, int start, int end) {
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if(nums[mid] >= target) {
end = mid;
} else {
// nums[mid] < target;
start = mid;
}
}
if(nums[start] == target) {
return start;
} else if(nums[end] == target) {
return end;
} else {
return -1;
}
}
private int findLastPosition(int[] nums, int target, int start, int end) {
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if(nums[mid] <= target) {
start = mid;
} else {
// nums[mid] > target;
end = mid;
}
}
if(nums[end] == target) {
return end;
} else if(nums[start] == target) {
return start;
} else {
return -1;
}
}
}
来源:CSDN
作者:flyatcmu
链接:https://blog.csdn.net/u013325815/article/details/104476864