Programmers

Programmers LV.2 더 맵게

Developer Garam.Choi 2020. 12. 28. 19:20

 

 

힙 우선순위로 나열해서 처리하면 될 것 같아서 했는데 테스트케이스 16번에서 에러가 나 원인을 확인해보고있었다.

 

수정 전

@org.junit.Test
    public void scoville(){
        int[] scovilles = { 1, 2, 3, 9, 10, 12 };
        int K = 7;

        Queue<Integer> que = new PriorityQueue<Integer>((o1, o2) -> Integer.compare(o1,o2));
        for(int scoville : scovilles){
            que.offer(scoville);
        }

        int answer = 0;
        int check = 0;
        while (que.size() > 1){
            if(que.peek() >= K){
                answer = check;
                break;
            }

            int o1 = que.poll();
            int o2 = que.poll();
            int tempCalc = o1 + (o2*2);
            que.offer(tempCalc);
            check++;

            if(que.size() == 1 && que.peek() < K){
                answer = -1;
            }

        }

        System.out.println(answer);
    }

 

16번 테스트 케이스를 scoville : [1,2,3] K : 11 로 잡고 수정했다.

 

@org.junit.Test
    public void scoville(){
        int[] scovilles = { 1, 2, 3 };
        int K = 11;

        Queue<Integer> que = new PriorityQueue<Integer>((o1, o2) -> Integer.compare(o1,o2));
        for(int scoville : scovilles){
            que.offer(scoville);
        }

        int answer = 0;
        int check = 0;
        while (que.size() > 1){
            if(que.peek() >= K){
                answer = check;
                break;
            }

            int o1 = que.poll();
            int o2 = que.poll();
            int tempCalc = o1 + (o2*2);
            que.offer(tempCalc);
            check++;

            if(que.size() == 1){
                if(que.peek() < K){
                    answer = -1;
                }else if( que.peek() >= K){
                    answer = 1;
                }
            }

        }

        System.out.println(answer);
    }

 

음식이 다섞여서 1개로 딱 맞춰질 경우가 존재해서 16번이 틀린것으로 보인다.