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]
已经排好了序,用二分查找。
重新实现 lower_bound 和 upper_bound/**
*
* @author dongb
* Search for a Range
* rebuild the lower_bound and upper_bound
* TC O(logn). SC O(1)
*
*/
public class Solution {
public static int[] searchRange(int[] nums, int target) {
int lower = lowerBound(nums, 0, nums.length, target);
int upper = upperBound(nums, 0, nums.length, target);
if (lower == nums.length || nums[lower] != target) {
return new int[]{-1, -1};
} else
return new int[]{lower, upper - 1};
}
public static int lowerBound(int[] nums, int first, int last, int target) {
while(first != last) {
int middle = first + (last - first) / 2;
if (target > nums[middle]) {
first = ++middle;
} else {
last = middle;
}
}
return first;
}
public static int upperBound(int[] nums, int first, int last, int target) {
while(first != last) {
int middle = first + (last - first) / 2;
if (target >= nums[middle]) { // this is the only difference between lowerBound
first = ++middle;
} else {
last = middle;
}
}
return first;
}
public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
int[] nums = new int[5];
for (int i = 0; i < nums.length; i++) {
nums[i] = cin.nextInt();
}
int target = cin.nextInt();
int[] answer = searchRange(nums, target);
for (int i = 0; i < answer.length; i++) {
System.out.println(answer[i]);
}
}
}