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 orderO(LogN).
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].
This article mainly deals with binary search, imitating lower_bound and upper_bound in STL. The general flow of the algorithm is to search for the target in binary search. If the target cannot be found, the system returns [-1,-1], find the first number equal to the target in the left half, and find the first number greater than the target in the right half.
1 class solution {2 public: 3 vector <int> searchrange (int A [], int N, int target) {4 vector <int> ans (2,-1 ); 5 If (! A | n <1) return ans; 6 int left = 0, Right = n-1; 7 while (left <= right) {8 int mid = left + (right-left) /2; 9 If (target = A [Mid]) {10 ans [0] = lower_bound (A, left, mid-1, target ); 11 ans [1] = upper_bound (A, Mid + 1, right, target)-1; 12 Return ans; 13} 14 if (target> A [Mid]) left = Mid + 1; 15 else right = mid-1; 16} 17 return ans; 18} 19 20 int lower_bound (int A [], int left, int right, int target) {// find the first number equal to target 21 While (left <= right) {22 int mid = left + (right-left)/2; 23 if (target> A [Mid]) Left = Mid + 1; 24 else right = mid-1; 25} 26 return right + 1; 27} 28 29 int upper_bound (int A [], int left, int right, int target) {// find the first number greater than target 30 While (left <= right) {31 int mid = left + (right-left)/2; 32 If (target> = A [Mid]) Left = Mid + 1; 33 else right = mid-1; 34} 35 return left; 36} 37 };
Search for a Range