-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy path0218_the_skyline_problem_(hard).js
More file actions
86 lines (70 loc) · 1.52 KB
/
0218_the_skyline_problem_(hard).js
File metadata and controls
86 lines (70 loc) · 1.52 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
/**
* 218. The Skyline Problem
*
* https://leetcode.com/problems/the-skyline-problem/
*
* The Skyline Problem
*/
Object.defineProperty(Array.prototype, 'first', {
get: function () {
return this[0];
},
});
Object.defineProperty(Array.prototype, 'last', {
get: function () {
return this[this.length - 1];
},
});
/**
* @param {number[][]} buildings
* @return {number[][]}
*/
const getSkyline = (buildings) => {
return helper(buildings, 0, buildings.length - 1);
};
/**
* @param {number[][]} buildings
* @param {number} lo
* @param {number} hi
* @return {number[][]}
*/
const helper = (buildings, lo, hi) => {
if (lo > hi) {
return [];
}
if (lo === hi) {
return [
[buildings[lo][0], buildings[lo][2]],
[buildings[lo][1], 0],
];
}
const mid = lo + Math.floor((hi - lo) / 2);
const left = helper(buildings, lo, mid);
const right = helper(buildings, mid + 1, hi);
let h1 = 0;
let h2 = 0;
const result = [];
while (left.length && right.length) {
let x, h;
if (left.first[0] < right.first[0]) {
[x, h1] = left.shift();
} else if (left.first[0] > right.first[0]) {
[x, h2] = right.shift();
} else {
[x, h1] = left.shift();
[x, h2] = right.shift();
}
h = Math.max(h1, h2);
if (result.length === 0 || result.last[1] != h) {
result.push([x, h]);
}
}
while (left.length) {
result.push(left.shift());
}
while (right.length) {
result.push(right.shift());
}
return result;
};
export { getSkyline };