[leetcode]Search for a Range
二分查找。找到后往左往右移。又说有种log(n)的算法是二分查找最左的,然后二分查找最右的。省却最后那部分O(n)的
public class Solution { public int[] searchRange(int[] A, int target) { // Start typing your Java solution below // DO NOT write main() function int pos = searchTarget(A, target, 0, A.length -1); if (pos == -1) return new int[]{-1,-1}; int start = 0; int end = A.length - 1; for (int i = pos - 1; i >= 0; i--) { if (A[i] != target) { start = i+1; break; } } for (int i = pos + 1; i < A.length; i++) { if (A[i] != target) { end = i - 1; break; } } return new int[]{start,end}; } public int searchTarget(int[] A, int target, int left, int right) { if (left > right) return -1; int mid = (left + right) / 2; if (A[mid] == target) return mid; if (A[mid] > target) return searchTarget(A, target, left, mid -1); else return searchTarget(A, target, mid+1, right); } }
这是参考答案,两次log(n)的查找:http://discuss.leetcode.com/questions/213/search-for-a-range
class Solution { public: vector<int> searchRange(int A[], int n, int target) { vector<int> range(2, -1); int lower = 0; int upper = n; int mid; // Search for lower bound while (lower < upper) { mid = (lower + upper) / 2; if (A[mid] < target) lower = mid + 1; else upper = mid; } // If the target is not found, return (-1, -1) if (A[lower] != target) return range; range[0] = lower; // Search for upper bound upper = n; while (lower < upper) { mid = (lower + upper) / 2; if (A[mid] > target) upper = mid; else lower = mid + 1; } range[1] = upper - 1; return range; } };