-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
find-the-number-of-ways-to-place-people-i.cpp
58 lines (54 loc) · 1.63 KB
/
find-the-number-of-ways-to-place-people-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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Time: O(n^2)
// Space: O(1)
// sort, array
class Solution {
public:
int numberOfPairs(vector<vector<int>>& points) {
sort(begin(points), end(points), [](const auto& a, const auto& b) {
return a[0] != b[0] ? a[0] < b[0] : a[1] > b[1];
});
int result = 0;
for (int i = 0; i < size(points); ++i) {
for (int j = i + 1, y = numeric_limits<int>::min(); j < size(points); ++j) {
if (points[i][1] < points[j][1]) {
continue;
}
if (points[j][1] > y) {
y = points[j][1];
++result;
}
}
}
return result;
}
};
// Time: O(n^3)
// Space: O(1)
// sort, array
class Solution2 {
public:
int numberOfPairs(vector<vector<int>>& points) {
sort(begin(points), end(points), [](const auto& a, const auto& b) {
return a[0] != b[0] ? a[0] < b[0] : a[1] > b[1];
});
int result = 0;
for (int i = 0; i < size(points); ++i) {
for (int j = i + 1, y = numeric_limits<int>::min(); j < size(points); ++j) {
if (points[i][1] < points[j][1]) {
continue;
}
bool valid = true;
for (int k = i + 1; k < j; ++k) {
if (points[i][1] >= points[k][1] && points[k][1] >= points[j][1]) {
valid = false;
break;
}
}
if (valid) {
++result;
}
}
}
return result;
}
};