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);
1 public class Solution { 2 public int[] searchRange(int[] A, int target) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 int idx = binarySearch(A, target); 6 int len = A.length; 7 int[] results = null; 8 if(idx == -1){ 9 results = new int[]{-1, -1}; 10 } else{ 11 int l = idx; 12 int r = idx; 13 while(l >= 0 && A[l] == target){ 14 l--; 15 } 16 l++; 17 18 while(r < len && A[r] == target){ 19 r++; 20 } 21 r--; 22 results = new int[]{l, r}; 23 } 24 return results; 25 } 26 27 public int binarySearch(int[] A, int target){ 28 int len = A.length; 29 int l = 0, r = len - 1; 30 while(l <= r){ 31 int mid = (l + r) / 2; 32 if(target == A[mid]) 33 return mid; 34 35 if(target > A[mid]){ 36 l = mid + 1; 37 } else { 38 r = mid - 1; 39 } 40 } 41 42 return -1; 43 } 44 }
google了下,要保证最坏情况下时间复杂度为O(lgn):进行两次二分搜索确定左右边界