leetcode -- Search for a Range (TODO)

时间:2023-03-09 09:32:08
leetcode -- Search for a Range (TODO)

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].

思路:

使用二分搜索找到target的idx,然后查看该idx的左右确定范围。

算法复杂度:

平均情况下是O(lgn);

最坏情况下数组中所有元素都相同O(n);

 public class Solution {
public int[] searchRange(int[] A, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int idx = binarySearch(A, target);
int len = A.length;
int[] results = null;
if(idx == -1){
results = new int[]{-1, -1};
} else{
int l = idx;
int r = idx;
while(l >= 0 && A[l] == target){
l--;
}
l++; while(r < len && A[r] == target){
r++;
}
r--;
results = new int[]{l, r};
}
return results;
} public int binarySearch(int[] A, int target){
int len = A.length;
int l = 0, r = len - 1;
while(l <= r){
int mid = (l + r) / 2;
if(target == A[mid])
return mid; if(target > A[mid]){
l = mid + 1;
} else {
r = mid - 1;
}
} return -1;
}
}

google了下,要保证最坏情况下时间复杂度为O(lgn):进行两次二分搜索确定左右边界