코딩 테스트

(Java) 프로그래머스 H-Index

로승리 2021. 12. 20. 23:59

문제의 카테고리가 정렬로 되어 있어 정렬을 이용해야 한다고 생각하고 문제를 읽기 시작했는데

이 문제에 정렬이 꼭 필요한가?? 하는 생각이 들어 생각나는 대로 코드를 작성했다.

문제도 이해하기 까다로운 부분이 몇 개 있어 고민하다가 약간 끼워 맞추듯이 작성했다.

정답으로 처리되긴 하나 다른 분 코드를 보니 왜 정렬을 하는지 알 수 있었다.


최종 코드

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Solution {
    public int solution(int[] citations) {
        int answer = 0;
        int h = 0;

        List<Integer> list = new ArrayList<>();
        for (int i = 0; i <= citations.length; i++) {
            int up = 0;
            int down = 0;
            for (int j = 0; j < citations.length; j++) {
                if(citations[j] >= h) {
                    up++;
                }
                if(citations[j] <= h) {
                    down++;
                }
            }
            if (h <= up) {
                list.add(h);
            }
            h++;
        }
        if(list.isEmpty()) {
            answer = 0;
        }
        answer = Collections.max(list);
        return answer;
    }
}

 

다른분 코드

import java.util.Arrays;

class Solution {
    public int solution(int[] citations) {
        int answer = 0;
        Arrays.sort(citations);
        for(int i=0; i<citations.length; i++){
            int smaller = Math.min(citations[i], citations.length-i);
            answer = Math.max(answer, smaller);
        }
        return answer;
    }
}