描述:
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]=0&&A[temp]==target) { i++; temp=index-i; } arr[0]=index-i+1; i=1; temp=index+i; while(temp