본문 바로가기

알고리즘

[프로그래머스] 정렬 > H-Index (자바)

프로그래머스 > 코딩테스트 연습 > 정렬 > H-Index

 

 

 

▶ 문제

1. 과학자가 발표한 논문의 인용 횟수를 담은 배열 → citations

2. n = citations.length

3. h만큼 인용된 논문의 횟수도 h편 이상, 이때 h의 최댓값은?

 

* H-Index 위키백과 보러가기 → 위키백과를 요약해보면

1. 배열 citations을 내림차순으로 정렬한다.

2. citations[i]가 위치보다 크거나 같은 마지막 위치를 찾는다 (=h)

3. 결과적으로 수식은 H-Index = max{citations[i] >= 위치}

 

 

▶ 처음 생각한 풀이

* H-Index = max{citations[i] >= 위치}, 이때 위치는 i+1 이므로 

1. 배열을 내림차순으로 정렬하고 → Arrays.sort(citations);

2. 배열의 길이만큼 돌려주는데 (citations.length)

3. citations[i] >= i+1 이면 answer = i+1 이다.

 

 

▶ 코드1 (잘못된 코드)

import java.util.*;

class Solution {
    public int solution(int[] citations) {
        int answer = 0;
        Arrays.sort(citations);
        
        for(int i = 0; i < citations.length; i++) {
            if(citations[i] >= i+1) {
                answer = i+1 ;
                break;
            }
        }
        
        return answer;
    }
}

→ 테스트케이스 [3, 0, 6, 1, 5]를 제외하고 모두 틀린 결과값이 나왔다...

[9, 7, 6, 2, 1]

[10, 8, 5, 4, 3]

(전부 값이 1이였음)

 

▶ 코드2

import java.util.*;

class Solution {
    public int solution(int[] citations) {
        int answer = 0;
        Arrays.sort(citations);
        
        int h;
        for(int i = 0; i < citations.length; i++) {
        h =  citations.length - i;

            if(citations[i] >=h) {
                answer = h ;
                break;
            }
        }
        
        return answer;
    }
}