leetcode: Search for a Range
http://oj.leetcode.com/problems/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].
思路:
先用二分法找到target出现的位置,然后不停的用二分法确定左右区间。
1 class Solution { 2 public: 3 int binarySearch(int A[], int start, int end, int target) { 4 while (start <= end) { 5 int mid = (start + end) / 2; 6 7 if (A[mid] == target) { 8 return mid; 9 } 10 else if (A[mid] < target) { 11 start = mid + 1; 12 } 13 else { 14 end = mid - 1; 15 } 16 } 17 18 return -1; 19 } 20 21 22 vector<int> searchRange(int A[], int n, int target) { 23 vector<int> result(2, -1); 24 int pos = binarySearch(A, 0, n - 1, target); 25 26 if (-1 == pos) { 27 return result; 28 } 29 30 int tmp_pos, start = pos, end = pos; 31 32 tmp_pos = pos - 1; 33 34 while (tmp_pos >= 0) { 35 tmp_pos = binarySearch(A, 0, tmp_pos, target); 36 37 if (-1 == tmp_pos) { 38 break; 39 } 40 else { 41 start = tmp_pos; 42 --tmp_pos; 43 } 44 } 45 46 tmp_pos = pos + 1; 47 48 while (tmp_pos < n) { 49 tmp_pos = binarySearch(A, tmp_pos, n - 1, target); 50 51 if (-1 == tmp_pos) { 52 break; 53 } 54 else { 55 end = tmp_pos; 56 ++tmp_pos; 57 } 58 } 59 60 result[0] = start; 61 result[1] = end; 62 63 return result; 64 } 65 };