-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0218_the_skyline_problem.rs
More file actions
94 lines (84 loc) · 2.73 KB
/
s0218_the_skyline_problem.rs
File metadata and controls
94 lines (84 loc) · 2.73 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#![allow(unused)]
pub struct Solution {}
impl Solution {
// Min Heap Time O(k log k) Space O(k)
pub fn get_skyline(mut buildings: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
use std::collections::BinaryHeap;
let mut heap: BinaryHeap<(i32, i32)> = BinaryHeap::with_capacity(buildings.len());
let mut valid = vec![false; buildings.len()];
let mut line: Vec<(i32, i32, bool, i32)> = Vec::with_capacity(2 * buildings.len());
let mut res: Vec<Vec<i32>> = vec![];
for (i, data) in buildings.iter().enumerate() {
line.push((data[0], i as i32, true, data[2]));
line.push((data[1], i as i32, false, data[2]));
}
// Sort by coordinate , untie by larger height
line.sort_unstable_by_key(|x| (x.0, -(x.3 as i64)));
for point in line {
let coord = point.0;
let i = point.1;
let is_start = point.2;
if is_start {
let height = buildings[i as usize][2];
valid[i as usize] = true;
heap.push((height, i));
res.push(vec![coord, heap.peek().unwrap().0]);
} else {
valid[i as usize] = false;
while let Some(&(_, j)) = heap.peek() {
if valid[j as usize] {
break;
}
heap.pop();
}
res.push(vec![coord, heap.peek().unwrap_or(&(0, 0)).0]);
}
}
// Remove all entries with the same coordinate but one
// (keep the one that appears last in the list)
let mut last_coord = -1;
res = res.into_iter().rev().filter(|x| {
if x[0] != last_coord {
last_coord = x[0];
return true;
}
return false;
}).collect::<Vec<Vec<i32>>>();
// Remove all entries with the same height but one
// (keep the one that appears first in the list)
let mut h = -1;
res = res.into_iter().rev().filter(|x|{
if x[1] != h {
h = x[1];
return true;
}
return false;
}).collect();
res
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_218() {
assert_eq!(
Solution::get_skyline(vec![
vec![2, 9, 10],
vec![3, 7, 15],
vec![5, 12, 12],
vec![15, 20, 10],
vec![19, 24, 8]
]),
vec![
vec![2, 10],
vec![3, 15],
vec![7, 12],
vec![12, 0],
vec![15, 10],
vec![20, 8],
vec![24, 0]
]
);
}
}