-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
minimum-moves-to-get-a-peaceful-board.cpp
49 lines (45 loc) · 1.21 KB
/
minimum-moves-to-get-a-peaceful-board.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
// Time: O(n)
// Space: O(n)
// counting sort, greedy
class Solution {
public:
int minMoves(vector<vector<int>>& rooks) {
const auto& count = [](const auto& cnt) {
int result = 0;
for (int x = 0, i = 0; x < size(cnt); ++x) {
for (int _ = 0; _ < cnt[x]; ++_) {
result += abs((i++) - x);
}
}
return result;
};
vector<int> cnt1(size(rooks)), cnt2(size(rooks));
for (const auto& x : rooks) {
++cnt1[x[0]];
++cnt2[x[1]];
}
return count(cnt1) + count(cnt2);
}
};
// Time: O(n)
// Space: O(n)
// prefix sum, greedy
class Solution2 {
public:
int minMoves(vector<vector<int>>& rooks) {
const auto& count = [](const auto& cnt) {
int result = 0;
for (int i = 0, bal = 0; i < size(cnt); ++i) {
bal += cnt[i] - 1;
result += abs(bal);
}
return result;
};
vector<int> cnt1(size(rooks)), cnt2(size(rooks));
for (const auto& x : rooks) {
++cnt1[x[0]];
++cnt2[x[1]];
}
return count(cnt1) + count(cnt2);
}
};