Skip to content

Commit c91ee3f

Browse files
authored
Create find-the-number-of-ways-to-place-people-ii.py
1 parent bb576c8 commit c91ee3f

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Time: O(n^2)
2+
// Space: O(1)
3+
4+
// sort, array
5+
class Solution {
6+
public:
7+
int numberOfPairs(vector<vector<int>>& points) {
8+
sort(begin(points), end(points), [](const auto& a, const auto& b) {
9+
return a[0] != b[0] ? a[0] < b[0] : a[1] > b[1];
10+
});
11+
12+
int result = 0;
13+
for (int i = 0; i < size(points); ++i) {
14+
for (int j = i + 1, y = numeric_limits<int>::min(); j < size(points); ++j) {
15+
if (points[i][1] < points[j][1]) {
16+
continue;
17+
}
18+
if (points[j][1] > y) {
19+
y = points[j][1];
20+
++result;
21+
}
22+
}
23+
}
24+
return result;
25+
}
26+
};
27+
28+
// Time: O(n^3)
29+
// Space: O(1)
30+
// sort, array
31+
class Solution2 {
32+
public:
33+
int numberOfPairs(vector<vector<int>>& points) {
34+
sort(begin(points), end(points), [](const auto& a, const auto& b) {
35+
return a[0] != b[0] ? a[0] < b[0] : a[1] > b[1];
36+
});
37+
38+
int result = 0;
39+
for (int i = 0; i < size(points); ++i) {
40+
for (int j = i + 1, y = numeric_limits<int>::min(); j < size(points); ++j) {
41+
if (points[i][1] < points[j][1]) {
42+
continue;
43+
}
44+
bool valid = true;
45+
for (int k = i + 1; k < j; ++k) {
46+
if (points[i][1] >= points[k][1] && points[k][1] >= points[j][1]) {
47+
valid = false;
48+
break;
49+
}
50+
}
51+
if (valid) {
52+
++result;
53+
}
54+
}
55+
}
56+
return result;
57+
}
58+
};

0 commit comments

Comments
 (0)