알고리즘 공부/프로그래머스

(Java)프로그래머스 코딩테스트 연습 - 힙(Heap) - 더 맵게

HRuler 2020. 10. 19. 22:08

1. 문제

https://programmers.co.kr/learn/courses/30/lessons/42626?language=java

 

코딩테스트 연습 - 더 맵게

매운 것을 좋아하는 Leo는 모든 음식의 스코빌 지수를 K 이상으로 만들고 싶습니다. 모든 음식의 스코빌 지수를 K 이상으로 만들기 위해 Leo는 스코빌 지수가 가장 낮은 두 개의 음식을 아래와 같��

programmers.co.kr

2. 나의 풀이

import java.util.PriorityQueue;

class Solution {
    public int solution(int[] scoville, int K) {
        int answer = 0;
        //System.out.println(check(scoville, K));
        PriorityQueue <Integer> q = new PriorityQueue();
        for(int imsi : scoville) {
        	q.add(imsi);
        }
        try {
        	while(check(q, K)) {
        		q.add(q.poll() + (q.poll() * 2));
        		answer += 1;
        	}
        }catch(Exception e){
        	answer = -1;
        }
        return answer;
    }
    
    boolean check(PriorityQueue <Integer> scoville, int K) {
    	boolean answer = false;
    	for(int imsi : scoville) {
    		if(imsi < K) {
    			answer = true;
    			break;
    		}
    	}
    	return answer;
    }
}

3. 다른 사람 풀이

import java.util.*;
class Solution {
    public int solution(int[] scoville, int K) {
        PriorityQueue<Integer> q = new PriorityQueue<>();

        for(int i = 0; i < scoville.length; i++)
            q.add(scoville[i]);

        int count = 0;
        while(q.size() > 1 && q.peek() < K){
            int weakHot = q.poll();
            int secondWeakHot = q.poll();

            int mixHot = weakHot + (secondWeakHot * 2);
            q.add(mixHot);
            count++;
        }

        if(q.size() <= 1 && q.peek() < K)
            count = -1;

        return count;
    }
}