์•Œ๊ณ ๋ฆฌ์ฆ˜/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;
    }
}