Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
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]
Example 3:
Input: nums = [], target = 0
Output: [-1,-1]
假設有一個已排序的整數數組 nums 為:[1, 2, 2, 3, 4, 4, 4, 5, 6],我們要找到目標元素 target 為 4 的起始索引和結束索引。
a.當尋找目標元素 4 的起始索引時:
b. 當尋找目標元素 4 的結束索引時:
最終,返回結果數組 [4, 6],表示目標元素 4 在已排序數組中的起始索引和結束索引分別為 4 和 6。
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = new int[2];
result[0] = findStartingIndex(nums, target);
result[1] = findEndingIndex(nums, target);
return result;
}
public int findStartingIndex(int[] nums, int target){
int index = -1;
int start = 0;
int end = nums.length-1;
while(start<=end){
int mid = start + (end-start)/2;
if(nums[mid] >= target){ //對於startingIndex而言,雖然找到了element,但仍希望往左移動尋找,找到前一個target數字
end = mid-1;
} else{
start = mid+1;
}
if(nums[mid]==target) index = mid;
}
return index;
}
public int findEndingIndex(int[] nums, int target){
int index = -1;
int start = 0;
int end = nums.length-1;
while(start<=end){
int mid = start + (end-start)/2;
if(nums[mid] <= target){ //對於endingIndex而言,雖然找到了element,但仍希望往右移動尋找,找到下一個target數字
start = mid +1;
} else{
end = mid-1;
}
if(nums[mid]==target) index = mid;
}
return index;
}
}
Time: O(log n) Space: O(1)