标签:search for a range binary search
描述:
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]
.
思路:
1.二分查找,找到value为target的一个元素的位置,找不到返回[-1,-1]
2.假设找到位置,且为index,分别向两边拓展即可。
代码:
public int[] searchRange(int[] A, int target) { int arr[]=new int[2]; Arrays.fill(arr, -1); if(A==null||A.length==0) return arr; int len=A.length; int start=0,end=len-1; int mid=0; int index=-1; while(start<=end) { mid=(start+end)/2; if(A[mid]==target) { index=mid; break; }else if(A[mid]<target) start=mid+1; else end=mid-1; } if(index==-1) return arr; int i=1,temp=index-i; while(temp>=0&&A[temp]==target) { i++; temp=index-i; } arr[0]=index-i+1; i=1; temp=index+i; while(temp<len&&A[temp]==target) { i++; temp=index+i; } arr[1]=index+i-1; return arr; }
标签:search for a range binary search
原文地址:http://blog.csdn.net/mnmlist/article/details/45788751