lintcode61- Search for a Range- medium
Given a sorted array of n integers, find the starting and ending position of a given target value.
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]
.
Challenge
O(log n) time.
二分查找法找first target,然后向后检索。
public class Solution { /* * @param A: an integer sorted array * @param target: an integer to be inserted * @return: a list of length 2, [index1, index2] */ public int[] searchRange(int[] A, int target) { // find the first int[] result = new int[2]; for (int i = 0; i < result.length; i++){ result[i] = -1; } if (A == null || A.length == 0){ return result; } int start = 0; int end = A.length - 1; while (start + 1 < end){ int mid = start + (end - start) / 2; if (target <= A[mid]){ end = mid; } else { start = mid; } } // search forward if (A[start] == target){ result[0] = start; result[1] = start; while (result[1] + 1 < A.length && A[result[1] + 1] == target){ result[1]++; } } else if (A[end] == target){ result[0] = end; result[1] = end; while (result[1] + 1 < A.length && A[result[1] + 1] == target){ result[1]++; } } return result; } }