์๊ณ ๋ฆฌ์ฆ/LeetCode
leetcode 218. The Skyline Problem
reumiii
2022. 9. 30. 11:18
๐ ๋ฌธ์
https://leetcode.com/problems/the-skyline-problem/
The Skyline Problem - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
๐ ๋์ ์ฝ๋
class Solution {
public List<List<Integer>> getSkyline(int[][] buildings) {
List<List<Integer>> answer = new ArrayList<List<Integer>>();
List<int[]> height = new ArrayList<int[]>(); // x์ขํ์ ๋์ด ์ ์ฅ
for(int i=0; i<buildings.length; i++) {
height.add(new int[] {buildings[i][0],buildings[i][2]}); // startX , height
height.add(new int[] {buildings[i][1],-buildings[i][2]});// endX , -height
}
// x์ขํ๋ฅผ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ / x์ขํ๊ฐ ๊ฐ๋ค๋ฉด ๋์ด๊ฐ ํฐ ์์ผ๋ก ์ ๋ ฌ
Collections.sort(height,(o1,o2)->{
if(o1[0] > o2[0]) return 1;
else if(o1[0] == o2[0] && o1[1] < o2[1]) return 1;
else return -1;
});
int nowHeight = 0; //ํ์ฌ ๋์ด
PriorityQueue<Integer> q = new PriorityQueue(Collections.reverseOrder()); // ํ์ฌ ์์น์ ๋น๋ฉ๋์ด ์ ์ฅ(๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌ)
q.add(0);
for(int i=0; i<height.size(); i++) {
if(height.get(i)[1] < 0) { // -height์ด๋ฉด q์์ ์ ๊ฑฐ
q.remove(-height.get(i)[1]);
}else {// ์๋๋ฉด q์ ์ถ๊ฐ
q.add(height.get(i)[1]);
}
if(nowHeight != q.peek()) { // ์ ์ผ ๋์ ๋์ด์ ํ์ฌ ๋์ด๊ฐ ๋ค๋ฅด๋ค๋ฉด answer์ ์ถ๊ฐ
nowHeight = q.peek();
List<Integer> list = new ArrayList(Arrays.asList(height.get(i)[0],nowHeight));
answer.add(list);
}
}
return answer;
}
}