-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupperbound_and_lowerbound.cpp
71 lines (63 loc) · 1.62 KB
/
upperbound_and_lowerbound.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# include <vector>
using namespace std;
// when the target is present
// 'ans' returns 0-based index position
int lowerBound(vector<int> &arr, int target) {
int ans = 0;
int n = arr.size();
// binary search
int l = 0, h = n - 1;
while (l <= h) {
int mid = l + (h - l)/2;
if (arr[mid] == target) {
ans = mid;
h = mid - 1;
} else if (arr[mid] > target) h = mid - 1;
else l = mid + 1;
}
return ans;
}
int upperBound(vector<int> &arr, int target) {
int ans = 0;
int n = arr.size();
int l = 0, h = n - 1;
while (l <= h) {
int mid = l + (h - l)/2;
if (arr[mid] == target) {
ans = mid;
l = mid + 1;
} else if (arr[mid] > target) h = mid - 1;
else l = mid + 1;
}
return ans;
}
// find closest element to target, when target is not present
int findClosest(vector<int> &arr, int target) {
int n = arr.size();
// corner cases
if (target <= arr[0]) return 0;
if (target >= arr[n - 1]) return (n - 1);
// main logic
int l = 0, h = arr.size() - 1;
int mid = 0;
while (l < h) {
mid = l + (h - l)/2;
if (arr[mid] == target) return mid;
if (target < arr[mid]) {
if (mid > 0 && target > arr[mid - 1]) {
return (getClosest(arr[mid - 1], arr[mid], target) == arr[mid - 1] ? (mid - 1) : mid);
}
h = mid;
} else {
if (mid < n - 1 && target < arr[mid + 1]) {
return (getClosest(arr[mid], arr[mid + 1], target) == arr[mid] ? mid : (mid + 1));
}
l = mid + 1;
}
}
return mid;
}
int getClosest(int val1, int val2, int target) {
if (abs(val1 - target) >= abs(val2 - target)) return val2;
return val1;
}