LeetCode 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]
.
二分法查找,虽然AC了,但写的不太好。
public class Solution { ArrayList<Integer> arrayList=new ArrayList<>(); int[] res=new int[]{-1,-1}; public int[] searchRange(int[] A, int target) { if (A.length==0) { return null; } int middle = (A.length-1)/2; int end=A.length-1; if (A[middle]>target) { search(A, 0, middle, target); }else if (A[middle]<target) { search(A, middle, end, target); } else { search(A, 0, middle, target); search(A, middle+1, end, target); } if (arrayList.isEmpty()) { return res; }else { res[0]=arrayList.get(0); res[1]=arrayList.get(arrayList.size()-1); return res; } } private void search(int[] A,int begin,int end,int target) { if(begin>end){ return; } if (begin==end) { if (A[begin]==target) { if (!arrayList.contains(begin)) { arrayList.add(begin); } } return; } int middle = (begin+end)/2; if (A[middle]>target) { search(A, begin, middle, target); return; } if (A[middle]<target) { search(A, middle+1, end, target); return; } if (A[middle]==target) { search(A, begin, middle, target); search(A, middle+1, end, target); return; } } }