Search for a Range
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]
.
A solution of o(logn). Do two runs of binary search for the index of largest element strictly less than target, and the index of largest element strictly less than target+1. The range is between this two indices.
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 if(A==null || A.length==0)return null; 6 int[] res = new int[2]; 7 res[0]=searchMaxLessThan(A,target,0,A.length-1); 8 res[1]=searchMaxLessThan(A,target+1,0,A.length-1); 9 if(res[0]==res[1]){ 10 res[0]=-1; 11 res[1]=-1; 12 }else{ 13 res[0]++; 14 } 15 return res; 16 } 17 18 public int searchMaxLessThan(int[] A, int target, int start, int end){ 19 20 if(start==end) return A[start]<target?start:start-1; 21 if(start==end-1) return A[end]<target?end:(A[start]<target?start:start-1); 22 int mid = (start+end)/2; 23 if(A[mid]>=target){ 24 end=mid-1; 25 }else{ 26 start=mid; 27 } 28 return searchMaxLessThan(A,target,start,end); 29 } 30 }
第二遍:
很巧妙的采用两次循环来做。
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 start = 0; 6 int end = A.length - 1; 7 int l = -1; 8 int r = -1; 9 while(start <= end){ 10 int mid = (start + end) / 2; 11 if(A[mid] == target) l = mid; 12 if(target <= A[mid]) end = mid - 1; 13 else start = mid + 1; 14 } 15 start = 0; 16 end = A.length - 1; 17 while(start <= end){ 18 int mid = (start + end) / 2; 19 if(A[mid] == target) r = mid; 20 if(target >= A[mid]) start = mid + 1; 21 else end = mid - 1; 22 } 23 return new int[]{l, r}; 24 } 25 }
第三遍:
1 public class Solution { 2 public int[] searchRange(int[] A, int target) { 3 int len = A.length; 4 int srt = 0, end = len - 1; 5 int left = -1, right = -1; 6 while(srt <= end){ 7 int mid = (srt + end) / 2; 8 if(A[mid] < target) srt = mid + 1; 9 else if(A[mid] > target) end = mid - 1; 10 else{ 11 left = mid; 12 end = mid - 1; 13 } 14 } 15 srt = 0; end = len - 1; 16 while(srt <= end){ 17 int mid = (srt + end) / 2; 18 if(A[mid] < target) srt = mid + 1; 19 else if(A[mid] > target) end = mid - 1; 20 else{ 21 right = mid; 22 srt = mid + 1; 23 } 24 } 25 return new int[]{left, right}; 26 } 27 }
posted on 2013-10-12 14:08 Step-BY-Step 阅读(152) 评论(0) 编辑 收藏 举报