프로그래머스 #42626 - 더 맵게

프로그래머스 #42626 - 더 맵게

[힙 개념]

1. 힙이란 ?
2. 힙 구현
3. 힙 삽입
4. 힙 삭제

[프로그래머스 #42626]

문제링크

1. 힙 직접 구현(테스트 케이스 일부 통과 실패)
public static int solution(int[] scoville, int K) {
		List<Integer> heap = Arrays.stream(scoville).boxed().sorted().collect(Collectors.toList());
        
    	// heap 계산을 쉽게하기 위해 0추가
        heap.add(0, 0);

        while(true){
            if(heap.get(1) > K) break;
            else if(heap.size() == 2){
                if(heap.get(1) > K) break;
                else return -1;
            }

            Integer minFirstVal = heap.remove(1);
            Integer minSecondVal = heap.remove(1);

            answer++;

            Integer newValue = minFirstVal + (2*minSecondVal);
            heap.add(newValue);
            int index = heap.size()-1;
            while(index >= 2 && heap.get(index) < heap.get(index/2)){
                Integer temp = heap.get(index);
                heap.set(index, heap.get(index/2));
                heap.set(index/2, temp);
                index = index/2;
            }
        }
}
2. PriorityQueue 사용(통과)
public static int solution(int[] scoville, int K) {
        int answer = 0;

        PriorityQueue<Integer> priorityQueue = Arrays.stream(scoville).;

        for(int val : scoville){
            priorityQueue.add(val);
        }

        while(priorityQueue.size() > 1){
            int firstVal = priorityQueue.poll();
            if(firstVal >= K) break;
            else {
                answer++;
                int secondVal = priorityQueue.poll();
                priorityQueue.add(firstVal + 2*secondVal);
            }
        }
        
        if(priorityQueue.size() == 1 && priorityQueue.peek() < K) answer = -1;
        return answer;
}

Comments

comments powered by Disqus