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
Solution 1: linear scan
Consideration
- start from the beginning, find the leftmost index of the target
- Then start from the end, find the rightmost index.
Time Complexity: O(n), space complexity: O(1)
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = {-1, -1};
//find the leftmost index
for(int i=0; i < nums.length; i++) {
if(nums[i] == target) {
res[0] = i;
break;
} else if(nums[i] > target) {
break;
}
}
//not found
if(res[0] == -1)
return res;
for(int i = nums.length-1; i>=res[0]; i--) {
if(nums[i] == target) {
res[1] = i;
break;
}
}
return res;
}
}
Solution 2: Binary search
Time Complexity: O(log (n)), space complexity: O(1)
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = {-1, -1};
int leftIndex = indexSearch(nums, target, true);
// 表示未找到target
if (leftIndex == nums.length || nums[leftIndex] != target) {
return result;
}
result[0] = leftIndex;
// 因为返回的是最右位置的下一个位置,需要进行减 1 操作
result[1] = indexSearch(nums, target, false) - 1;
return result;
}
private int indexSearch(int[] nums, int target, boolean isLeft) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] == target && isLeft) { // 如果是查最左位置,则应继续在左半部分查找,否则在右半部分查找
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
}
References
1.https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/