[Programmers] 디스크 컨트롤러 - 힙(Heap)

동민·2021년 3월 11일
import java.util.Arrays;
import java.util.PriorityQueue;

// 디스크 컨트롤러 - 힙(Heap)
public class DiskController {
	public int solution(int[][] jobs) {
		int answer = 0, time = 0, index = 0;
		
		Arrays.sort(jobs, (o1, o2) -> o1[0] - o2[0]); // 시간 순으로 정렬. 람다식; Object[][0] 오름차순 정렬
		PriorityQueue<int[]> heap = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]); // 작업이 짧은 순으로 정렬. 람다식; PriorityQueue<int[]> 형태 정렬 (우선순위 : int[][1] 오름차순) 

		while (index < jobs.length || !heap.isEmpty()) {
			while (index < jobs.length && time >= jobs[index][0]) { 
				heap.offer(jobs[index++]); // 현재 time보다 작은 job들을 힙에 삽입
			}
			if (heap.isEmpty()) {
				time = jobs[index][0];
			} else {
				answer += time - heap.peek()[0] + heap.peek()[1];
				time += heap.poll()[1];
			}
		}
		return answer / jobs.length;
	}
}
PriorityQueue<int[]> heap = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]);
=> 람다식; PriorityQueue<int[]> 형태 정렬 (우선순위 : int[][1] 오름차순)

Arrays.sort(matrix, (o1, o2) -> o1[0] - o2[0]);
=> 람다식; matrix가 2차원 배열일 때, Object[][0] 오름차순 정렬
profile
BE Developer

0개의 댓글