binary search
1 public class Solution { 2 public int[] searchRange(int[] A, int target) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 int[] result = new int[2]; 6 if(A == null){ 7 result[0] = -1; 8 result[1] = -1; 9 return result; 10 } 11 12 13 int start = search(A, ((double)target)-0.5, 0, A.length); 14 int end = search(A, ((double)target)+0.5, 0, A.length); 15 if(start == end){ 16 result[0] = -1; 17 result[1] = -1; 18 return result; 19 } 20 else{ 21 result[0] = start; 22 result[1] = end - 1; 23 return result; 24 } 25 } 26 27 private int search(int[] A, double target, int start, int end){ 28 if(start >= end) 29 return start; 30 int mid = (start + end) / 2; 31 if(target == A[mid]) 32 return mid; 33 else if(target < A[mid]) 34 return search(A, target, start, mid); 35 else 36 return search(A, target, mid+1, end); 37 } 38 }