-
Notifications
You must be signed in to change notification settings - Fork 9
/
SearchRange.cpp
45 lines (39 loc) · 1.33 KB
/
SearchRange.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
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]. Example: Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].
*/
int binarySearch(const vector<int>& A, int key, bool searchFirst){
int start = 0;
int end = A.size()-1;
int mid;
int result = -1;
while(start <= end){
mid = start + (end-start)/2;
if(A[mid] == key){
result = mid;
if(searchFirst){
end = mid-1;
}
else{
start = mid+1;
}
}
else if(A[mid] > key){
end = mid-1;
}
else{ // A[mid] < key
start = mid+1;
}
}
return result;
}
vector<int> Solution::searchRange(const vector<int> &A, int B) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
vector<int> sol;
sol.push_back(binarySearch(A, B, true));
sol.push_back(binarySearch(A, B, false));
return sol;
}