-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday18.cpp
More file actions
134 lines (120 loc) · 2.89 KB
/
day18.cpp
File metadata and controls
134 lines (120 loc) · 2.89 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include<bits/stdc++.h>
using namespace std;
//int search(vector<int> &nums, int target) {
// int n = nums.size();
// int high = n - 1;
// int low = 0;
//
// while (low <= high) {
// int mid = (high + low) / 2;
// if (nums[mid] == target) {
// return mid;
// } else if (nums[mid] >= target) {
// high = mid - 1;
// } else {
// low = mid + 1;
// }
// }
// return -1;
//}
//
//vector<int> searchRange(vector<int> &nums, int target) {
// int n = nums.size();
// int high = n - 1;
// int low = 0;
// int ans = n;
// int last = n;
// vector<int> temp = {};
// vector<int> nest = {-1, -1};
// int val = search(nums, target);
// if (val != -1) {
// while (low <= high) {
// int mid = (high + low) / 2;
// if (nums[mid] >= target) {
// ans = mid;
// last = mid + 1;
// high = mid - 1;
// } else {
// low = mid + 1;
// }
// }
// temp.push_back(ans);
// temp.push_back(last);
// nums = temp;
// return nums;
// } else {
// nums = nest;
// return nums;
// }
//
//}
//approach 2
int lowerBound(vector<int> arr, int n, int x) {
int low = 0, high = n - 1;
int ans = n;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] >= x) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
int upperBound(vector<int> &arr, int n, int x) {
int low = 0, high = n - 1;
int ans = n;
while (low <= high) {
int mid = (low + high) / 2;
// maybe an answer
if (arr[mid] > x) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
vector<int> searchRange(vector<int> &nums, int target) {
int n = nums.size();
int lb = lowerBound(nums, n, target);
if (lb == n || nums[lb] != target) {
return {-1, -1};
}
return {lb, upperBound(nums, n, target) - 1};
}
int countFreq(vector<int> &arr, int target) {
// code here
int n = arr.size();
int lb = lowerBound(arr, n, target);
if (lb == n || arr[lb] != target) {
return 0;
}
int ans = (upperBound(arr, n, target) - 1) - lb + 1;
return ans;
}
int minOperations(vector<int> &nums, int k) {
int n = nums.size();
int counter = 0;
for (int i = 0; i < n; i++) {
if (nums[i] < k) {
counter++;
}
}
return counter;
}
int main() {
vector<int> nums = {5, 7, 7, 8, 8, 8, 8, 8, 10};
int target = 8;
vector<int> ans = searchRange(nums, target);
cout << minOperations(nums, target) << endl;
for (auto it: ans) {
cout << it << " ";
}
cout << endl;
cout << countFreq(nums, target);
return 0;
}