Skip to content

Commit 1817e40

Browse files
authored
Create flower-planting-with-no-adjacent.cpp
1 parent a7e31f9 commit 1817e40

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) {
7+
vector<int> result(N);
8+
vector<vector<int>> G(N);
9+
for (const auto& path : paths) {
10+
int x = path[0], y = path[1];
11+
G[x - 1].emplace_back(y - 1);
12+
G[y - 1].emplace_back(x - 1);
13+
}
14+
for (int i = 0; i < N; ++i) {
15+
unordered_set<int> candidates = {1, 2, 3, 4};
16+
for (const auto& j : G[i]) {
17+
candidates.erase(result[j]);
18+
}
19+
result[i] = *(candidates.cbegin());
20+
}
21+
return result;
22+
}
23+
};

0 commit comments

Comments
 (0)