标签:
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]
.
[Solution]
二分法,A[middle] == target时向左右延伸,其他情况和二分法一致.
1 vector<int> searchRange(int A[], int n, int target) 2 { 3 int left = 0, right = n - 1, middle = (left + right) / 2; 4 vector <int> range(2, -1); 5 6 while (left <= right) 7 { 8 middle = (left + right) / 2; 9 if (A[middle] == target) 10 { 11 left = middle - 1; 12 right = middle + 1; 13 while (left >= 0 && A[left] == target) 14 left--; 15 while (right < n && A[right] == target) 16 right++; 17 break; 18 } 19 if (A[middle] < target) 20 left = middle + 1; 21 else 22 right = middle - 1; 23 } 24 25 if (left <= right) 26 { 27 range[0] = left + 1; 28 range[1] = right - 1; 29 } 30 return range; 31 }
leetcode 34. Search for a Range
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4276057.html