Sweep Line
, Heap
, Segment Tree
, Binary Indexed Tree
Hard
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).
The geometric information of each building is represented by a triplet of integers[Li, Ri, Hi]
, whereLi
andRi
are the x coordinates of the left and right edge of the ith building, respectively, andHi
is its height. It is guaranteed that0 ≤ Li, Ri ≤ INT_MAX
,0 < Hi ≤ INT_MAX
, andRi - Li > 0
. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.
For instance, the dimensions of all buildings in Figure A are recorded as:[ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ]
.
The output is a list of "key points " (red dots in Figure B) in the format of[ [x1,y1], [x2, y2], [x3, y3], ... ]
that uniquely defines a skyline.A key point is the left endpoint of a horizontal line segment . Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.
For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ]
.
Notes:
The number of buildings in any input list is guaranteed to be in the range [0, 10000]
.
The input list is already sorted in ascending order by the left x position Li
.
The output list must be sorted by the x position.
There must be no consecutive horizontal lines of equal height in the output skyline. For instance,
[...[2 3], [4 5], [7 5], [11 5], [12 7]...]
is not acceptable; the three lines of height 5 should be merged into one in the final output as such:
[...[2 3], [4 5], [12 7], ...]
Solution & Analysis
Sweep Line + Priority Queue
思路
先将buildings[]转化为一系列 critcal points,并且根据点的坐标以及高度排序。一个trick是,将起始点对应的高度设成负值,而终止点的高度设为正值。当然也可以多设定一个位,用来区分起始点和终止点。
再遍历每一个点,并且用PriorityQueue来保存当前的点所对应的建筑的高度,并且每次选取最高的那一个(利用PriorityQueue的排序特性),加入结果列表中即可。
对于那个把起始点高度变成负数,还有一个很巧妙的原因,就是假设如果有三个大楼宽度都一样,叠在一起,只是高度不一样的话,起始点要从大往小读,这样才能保证不会产生三个critical points,而对于结束点,要从小往大读,不然还是会产生三个critical points。把起始点高度变成负数再排序,就很好的解决了顺序这个问题。
pq.remove()是O(n) time, 因此相比之下用TreeMap可以获得O(logn)的remove()时间复杂度
158 ms
Copy class Solution {
public List < int []> getSkyline ( int [][] buildings) {
List < int []> result = new ArrayList <>();
List < int []> heights = new ArrayList <>();
for ( int [] building : buildings) {
heights . add ( new int [] {building[ 0 ] , - building[ 2 ]});
heights . add ( new int [] {building[ 1 ] , building[ 2 ]});
}
Collections . sort (heights , (a , b) -> {
if (a[ 0 ] == b[ 0 ]) {
return a[ 1 ] - b[ 1 ];
}
return a[ 0 ] - b[ 0 ];
});
PriorityQueue < Integer > pq = new PriorityQueue < Integer >((a , b) -> b - a);
pq . offer ( 0 );
int prev = 0 ;
for ( int [] h : heights) {
if (h[ 1 ] < 0 ) {
pq . offer ( - h[ 1 ]);
} else {
pq . remove (h[ 1 ]);
}
int cur = pq . peek ();
if (cur != prev) {
result . add ( new int [] {h[ 0 ] , cur});
prev = cur;
}
}
return result;
}
}
Sweep Line + TreeMap (Time complexity improved compare to Priority Queue)
Copy public class Solution {
public List < int []> getSkyline ( int [][] buildings) {
List < int []> heights = new ArrayList <>();
for ( int [] b : buildings) {
heights . add ( new int []{b[ 0 ] , - b[ 2 ]});
heights . add ( new int []{b[ 1 ] , b[ 2 ]});
}
Collections . sort (heights , (a , b) -> (a[ 0 ] == b[ 0 ]) ? a[ 1 ] - b[ 1 ] : a[ 0 ] - b[ 0 ]);
TreeMap < Integer , Integer > heightMap = new TreeMap <>( Collections . reverseOrder ());
heightMap . put ( 0 , 1 );
int prevHeight = 0 ;
List < int []> skyLine = new LinkedList <>();
for ( int [] h : heights) {
if (h[ 1 ] < 0 ) {
Integer cnt = heightMap . get ( - h[ 1 ]);
cnt = ( cnt == null ) ? 1 : cnt + 1 ;
heightMap . put ( - h[ 1 ] , cnt);
} else {
Integer cnt = heightMap . get (h[ 1 ]);
if (cnt == 1 ) {
heightMap . remove (h[ 1 ]);
} else {
heightMap . put (h[ 1 ] , cnt - 1 );
}
}
int currHeight = heightMap . firstKey ();
if (prevHeight != currHeight) {
skyLine . add ( new int []{h[ 0 ] , currHeight});
prevHeight = currHeight;
}
}
return skyLine;
}
}
Linked List
2 ms
Copy class Solution {
class KeyPoint {
public int key;
public int height;
public KeyPoint next = null ;
public KeyPoint ( int key , int height) {
this . key = key;
this . height = height;
}
}
public List < int []> getSkyline ( int [][] buildings) {
List < int []> res = new ArrayList <>();
KeyPoint dummy = new KeyPoint( - 1 , 0 ) ; // dummy head
KeyPoint pre = dummy;
for ( int [] bd : buildings) {
int L = bd[ 0 ];
int R = bd[ 1 ];
int H = bd[ 2 ];
while ( pre . next != null && pre . next . key <= L)
pre = pre . next ;
int preH = pre . height ;
if ( pre . key == L)
pre . height = Math . max ( pre . height , H);
else if ( pre . height < H) {
KeyPoint next = pre . next ;
pre . next = new KeyPoint(L , H) ;
pre = pre . next ;
pre . next = next;
}
KeyPoint preIter = pre;
KeyPoint curIter = pre . next ;
while (curIter != null && curIter . key < R) {
preH = curIter . height ;
curIter . height = Math . max ( curIter . height , H);
if ( curIter . height == preIter . height )
preIter . next = curIter . next ;
else
preIter = curIter;
curIter = curIter . next ;
}
if ( preIter . height != preH && preIter . key != R && (curIter == null || curIter . key != R)) {
KeyPoint next = preIter . next ;
preIter . next = new KeyPoint(R , preH) ;
preIter . next . next = next;
}
}
KeyPoint first = dummy;
KeyPoint second = dummy . next ;
while (second != null ) {
if ( second . height != first . height )
res . add ( new int []{ second . key , second . height });
first = first . next ;
second = second . next ;
}
return res;
}
}
Segment Tree
34 ms
Copy class Solution {
public class Node {
Node left , right;
int start , end , height;
public Node ( int start , int end) {
this . start = start;
this . end = end;
height = 0 ;
}
}
public List < int []> getSkyline ( int [][] buildings) {
List < int []> result = new ArrayList <>();
Set < Integer > set = new HashSet <>();
for ( int [] b : buildings){
set . add (b[ 0 ]);
set . add (b[ 1 ]);
}
List < Integer > positions = new ArrayList <>(set);
Collections . sort (positions);
Map < Integer , Integer > map = new HashMap <>();
for ( int i = 0 ; i < positions . size (); i ++ ){
map . put ( positions . get (i) , i);
}
Node root = buildTree( 0 , positions . size() - 1 ) ;
for ( int [] b : buildings){
add(root , map . get(b[ 0 ]) , map . get(b[ 1 ]) , b[ 2 ]) ;
}
explore(result , positions , root) ;
if ( positions . size () > 0 ){
result . add ( new int []{ positions . get ( positions . size () - 1 ) , 0 });
}
return result;
}
public Node buildTree ( int start , int end) {
if (start > end){
return null ;
}
Node root = new Node(start , end) ;
if (start + 1 < end){
int mid = (start + end) / 2 ;
root . left = buildTree(start , mid) ;
root . right = buildTree(mid , end) ;
}
return root;
}
public void add ( Node root , int start , int end , int height) {
if (root == null || start >= root . end || end <= root . start || root . height > height){
return ;
}
if ( root . left == null && root . right == null ){
root . height = height;
} else {
add( root . left , start , end , height) ;
add( root . right , start , end , height) ;
root . height = Math . min ( root . left . height , root . right . height );
}
}
public void explore ( List < int []> result , List < Integer > positions , Node node){
if (node == null ){
return ;
}
if ( node . left == null && node . right == null && ( result . size () == 0 || result . get ( result . size () - 1 )[ 1 ] != node . height )){
result . add ( new int []{ positions . get ( node . start ) , node . height });
} else {
explore(result , positions , node . left ) ;
explore(result , positions , node . right ) ;
}
}
}
Divide and Conquer
5 ms, faster than 99.22%, 42.8 MB, less than 89.42%
From GeeksforGeeks: https://www.geeksforgeeks.org/the-skyline-problem-using-divide-and-conquer-algorithm/
We can find Skyline in Θ(nLogn) time using Divide and Conquer . The idea is similar to Merge Sort , divide the given set of buildings in two subsets. Recursively construct skyline for two halves and finally merge the two skylines.
Time complexity of above recursive implementation is same as Merge Sort. T(n) = T(n/2) + Θ(n) Solution of above recurrence is Θ(nLogn)
How to Merge two Skylines?
The idea is similar to merge of merge sort, start from first strips of two skylines, compare x coordinates. Pick the strip with smaller x coordinate and add it to result. The height of added strip is considered as maximum of current heights from skyline1 and skyline2.
Copy public class Solution {
public List < int []> getSkyline ( int [][] buildings) {
if ( buildings . length == 0 )
return new LinkedList < int []>();
return recurSkyline(buildings , 0 , buildings . length - 1 ) ;
}
private LinkedList < int []> recurSkyline ( int [][] buildings , int p , int q) {
if (p < q) {
int mid = p + (q - p) / 2 ;
return merge(recurSkyline(buildings , p , mid) ,
recurSkyline(buildings , mid + 1 , q)) ;
} else {
LinkedList < int []> rs = new LinkedList < int []>();
rs . add ( new int [] { buildings[p][ 0 ] , buildings[p][ 2 ] });
rs . add ( new int [] { buildings[p][ 1 ] , 0 });
return rs;
}
}
private LinkedList < int []> merge ( LinkedList < int []> l1 , LinkedList < int []> l2) {
LinkedList < int []> rs = new LinkedList < int []>();
int h1 = 0 , h2 = 0 ;
while ( l1 . size () > 0 && l2 . size () > 0 ) {
int x = 0 , h = 0 ;
if ( l1 . getFirst ()[ 0 ] < l2 . getFirst ()[ 0 ]) {
x = l1 . getFirst ()[ 0 ];
h1 = l1 . getFirst ()[ 1 ];
h = Math . max (h1 , h2);
l1 . removeFirst ();
} else if ( l1 . getFirst ()[ 0 ] > l2 . getFirst ()[ 0 ]) {
x = l2 . getFirst ()[ 0 ];
h2 = l2 . getFirst ()[ 1 ];
h = Math . max (h1 , h2);
l2 . removeFirst ();
} else {
x = l1 . getFirst ()[ 0 ];
h1 = l1 . getFirst ()[ 1 ];
h2 = l2 . getFirst ()[ 1 ];
h = Math . max (h1 , h2);
l1 . removeFirst ();
l2 . removeFirst ();
}
if ( rs . size () == 0 || h != rs . getLast ()[ 1 ]) {
rs . add ( new int [] { x , h });
}
}
rs . addAll (l1);
rs . addAll (l2);
return rs;
}
}
Divide and Conquer 6ms
Copy class Solution {
public List < int []> getSkyline ( int [][] b) {
return helper(b , 0 , b . length - 1 ) ;
}
List < int []> helper ( int [][] b , int s , int e) {
if (s > e) return new ArrayList <>();
if (s == e) {
List < int []> res = new ArrayList <>();
res . add ( new int []{b[s][ 0 ] , b[s][ 2 ]});
res . add ( new int []{b[s][ 1 ] , 0 });
return res;
}
int mid = s + (e - s) / 2 ;
return mergeSkyline(helper(b , s , mid) , helper(b , mid + 1 , e)) ;
}
List < int []> mergeSkyline ( List < int []> a , List < int []> b) {
List < int []> res = new ArrayList <>();
int cur_h = 0 , cur_h1 = 0 , cur_h2 = 0 , i1 = 0 , i2 = 0 ;
while (i1 < a . size () && i2 < b . size ()) {
int [] na = a . get (i1) , nb = b . get (i2);
int x = - 1 ;
if (na[ 0 ] < nb[ 0 ]) {
cur_h = Math . max (cur_h2 , na[ 1 ]);
x = na[ 0 ];
cur_h1 = na[ 1 ];
i1 ++ ;
} else if (na[ 0 ] > nb[ 0 ]) {
cur_h = Math . max (cur_h1 , nb[ 1 ]);
x = nb[ 0 ];
cur_h2 = nb[ 1 ];
i2 ++ ;
} else {
cur_h = Math . max (na[ 1 ] , nb[ 1 ]);
x = nb[ 0 ];
cur_h1 = na[ 1 ];
cur_h2 = nb[ 1 ];
i1 ++ ;
i2 ++ ;
}
if ( res . size () > 0 && res . get ( res . size () - 1 )[ 1 ] == cur_h) continue ;
res . add ( new int []{x , cur_h});
}
while (i1 < a . size ()) res . add ( a . get (i1 ++ ));
while (i2 < b . size ()) res . add ( b . get (i2 ++ ));
return res;
}
}
Reference