forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
put-boxes-into-the-warehouse-i.cpp
42 lines (40 loc) · 1.04 KB
/
put-boxes-into-the-warehouse-i.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
// Time: O(nlogn)
// Space: O(1)
class Solution {
public:
int maxBoxesInWarehouse(vector<int>& boxes, vector<int>& warehouse) {
sort(rbegin(boxes), rend(boxes));
int result = 0;
for (const auto& h : boxes) {
if (h > warehouse[result]) {
continue;
}
if (++result == size(warehouse)) {
break;
}
}
return result;
}
};
// Time: O(nlogn + m)
// Space: O(1)
class Solution2 {
public:
int maxBoxesInWarehouse(vector<int>& boxes, vector<int>& warehouse) {
sort(begin(boxes), end(boxes));
for (int i = 1; i < size(warehouse); ++i) {
warehouse[i] = min(warehouse[i], warehouse[i - 1]);
}
int result = 0, curr = 0;
for (int i = size(warehouse) - 1; i >= 0; --i) {
if (boxes[curr] > warehouse[i]) {
continue;
}
++result;
if (++curr == size(boxes)) {
break;
}
}
return result;
}
};