Problem
Given a sorted array of integers, 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].
For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].
Solution (JAVA)
public class Solution {
public int[] searchRange(int[] nums, int target) {
// 找到左邊界
int front = search(nums, target, "front");
// 找到右邊界
int rear = search(nums, target, "rear");
int[] res = {front, rear};
return res;
}
public int search(int[] nums, int target, String type){
int min = 0, max = nums.length - 1;
while(min <= max){
int mid = min + (max - min) / 2;
if(nums[mid] > target){
max = mid - 1;
} else if(nums[mid] < target){
min = mid + 1;
} else {
// 對于找左邊的情況,要判斷左邊的數(shù)是否重復(fù)
if(type == "front"){
if(mid == 0) return 0;
if(nums[mid] != nums[mid - 1]) return mid;
max = mid - 1;
} else {
// 對于找右邊的情況,要判斷右邊的數(shù)是否重復(fù)
if(mid == nums.length - 1) return nums.length - 1;
if(nums[mid] != nums[mid + 1]) return mid;
min = mid + 1;
}
}
}
//沒找到該數(shù)返回-1
return -1;
}
}
Discussion
這道題的本質(zhì)是就是找到相同值的上下限位置,基本的方法就是二分查找。在找到第一個值之后,我們需要確定這個值的上下位置。在子區(qū)間中,我們既可以繼續(xù)使用二分查找,也可以使用線性的查找方式。(這里的結(jié)局方案顯然是使用了二分的方式)