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]
.
Example
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
Solution:
1 public class Solution { 2 /** 3 *@param A : an integer sorted array 4 *@param target : an integer to be inserted 5 *return : a list of length 2, [index1, index2] 6 */ 7 public ArrayList<Integer> searchRange(ArrayList<Integer> A, int target) { 8 ArrayList<Integer> res = new ArrayList<Integer>(); 9 int start = -1, end = -1; 10 int p1 = 0, p2 = A.size()-1; 11 //find start point. 12 while (p1<=p2){ 13 int mid = (p1+p2)/2; 14 15 if (A.get(mid)==target){ 16 if (mid==0 || A.get(mid-1)!=target){ 17 start = mid; 18 break; 19 } else { 20 p2 = mid-1; 21 } 22 } else if (A.get(mid)>target) 23 p2 = mid-1; 24 else p1 = mid+1; 25 } 26 27 //find end point. 28 p1 = 0; 29 p2 = A.size()-1; 30 while (p1<=p2){ 31 int mid = (p1+p2)/2; 32 33 if (A.get(mid)==target){ 34 if (mid==A.size()-1 || A.get(mid+1)!=target){ 35 end = mid; 36 break; 37 } else p1 = mid+1; 38 } else if (A.get(mid)>target) 39 p2 = mid-1; 40 else p1 = mid+1; 41 } 42 43 res.add(start); 44 res.add(end); 45 46 return res; 47 } 48 }