given a sorted array of integers, find the starting and ending position of a Given target value.
your algorithm ' s runtime complexity must is 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, ten] and target value 8,
return [3, 4].
My problem-solving idea is: First find the target element with a binary search, then find the starting point in the first half of the zoomed-out area using two-point lookup, and find the endpoint using the binary lookup in the second half.
My C + + code is implemented as follows:
vector<int> searchrange (int a[], int n, int target) { vector<int> range (2,-1); int start = 0, end = n-1; while (start <= end) { int mid = (start + end) >> 1; if (a[mid] = = target) { int start1 = start, End1 = mid; while (Start1 <= end1) { int mid1 = (Start1 + end1) >> 1; if (a[mid1] = = target) End1 = mid1-1; else Start1 = mid1 + 1; } Range[0] = Start1; Start1 = Mid, End1 = end; while (Start1 <= end1) { int mid1 = (Start1 + end1) >> 1; if (a[mid1] = = target) Start1 = mid1 + 1; else End1 = mid1-1; } RANGE[1] = start1-1; break; } else if (A[mid] > Target) end = Mid-1; else start = mid + 1; } return range;}
I saw a very ingenious solution on the discuss:
you can choose double numbers T-0.5 and t+0.5 for Target T, and then binary search positions For the double numbers in the integer array (suppose the position be a and B respectively), then the answer is [a, b 1]. For example, for-input [5,7,7,8,8,10], you can search position for number 7.5 and 8.5 using Binary-search, and the Res Ult is 3 and 5, by which the answer [3,4] is easily obtained.
According to the above ideas I made the following implementation:
Class Solution {public: vector<int> searchrange (int a[], int n, int target) { vector<int> range (2); C2/>int start = BinarySearch (A, N, (double) target-0.5); int end = BinarySearch (A, N, (double) target + 0.5); Range[0] = (End > Start? Start:-1); RANGE[1] = (End > Start end-1:-1); return range; } Private: int binarysearch (int a[], int n, double target) { int start = 0, end = n-1; while (start <= end) { int mid = (start + end) >> 1; if (double) a[mid] > Target) end = Mid-1; else start = mid + 1; } return start; };
Leetcode[array]: Search for a Range