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].
題意:給定有序數組,找到目標元素出現的起始位置和終止位置,若沒有出現則返回-1,-1
解決思路:二分查找找到目標元素出現位置,然後找目標元素+1的數出現的元素的位置,減去1就是最後的結果了
代碼:
public class Solution {
public int[] searchRange(int[] nums, int target) {
int left = binarySearch(nums, target);
if(left == nums.length || nums[left] != target){
return new int[]{-1, -1};
}
return new int[]{left, binarySearch(nums, target + 1) - 1};
}
private int binarySearch(int[] nums, int target){
int count = nums.length;
int step = 0;
int left = 0;
int mid = 0;
while(count > 0){
step = count >> 1;
mid = left + step;
if(nums[mid] < target){
left = mid + 1;
count -= (step + 1);
}else{
count = step;
}
}
return left;
}
}