forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget-biggest-three-rhombus-sums-in-a-grid.cpp
46 lines (44 loc) · 1.73 KB
/
get-biggest-three-rhombus-sums-in-a-grid.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
// Time: O(m * n * min(m, n))
// Space: O(m * n)
class Solution {
public:
vector<int> getBiggestThree(vector<vector<int>>& grid) {
static const int K = 3;
vector<vector<int>> left{grid}, right{grid};
for (int i = 1; i < size(grid); ++i) {
for (int j = 0; j < size(grid[0]) - 1; ++j) {
left[i][j] += left[i - 1][j + 1];
}
}
for (int i = 1; i < size(grid); ++i) {
for (int j = 1; j < size(grid[0]); ++j) {
right[i][j] += right[i - 1][j - 1];
}
}
priority_queue<int, vector<int>, greater<int>> min_heap;
unordered_set<int> lookup;
for (int k = 0; k <= (min(size(grid), size(grid[0])) + 1) / 2; ++k) {
for (int i = k; i < size(grid) - k; ++i) {
for (int j = k; j < size(grid[0]) - k; ++j) {
int total = k ? ((left[i][j - k] - left[i - k][j]) + (right[i][j + k] - right[i - k][j]) + grid[i - k][j]) +
((left[i + k][j] - left[i][j + k]) + (right[i + k][j] - right[i][j - k]) - grid[i + k][j])
: grid[i][j];
if (lookup.count(total)) {
continue;
}
lookup.emplace(total);
min_heap.emplace(total);
if (size(min_heap) == K + 1) {
lookup.erase(min_heap.top()); min_heap.pop();
}
}
}
}
vector<int> result;
while (!empty(min_heap)) {
result.emplace_back(min_heap.top()); min_heap.pop();
}
reverse(begin(result), end(result));
return result;
}
};