[Programmers] H-index

최도혁·2023년 3월 28일

코딩테스트 준비

목록 보기
3/7

문제

H-Index는 과학자의 생산성과 영향력을 나타내는 지표입니다. 어느 과학자의 H-Index를 나타내는 값인 h를 구하려고 합니다. 위키백과1에 따르면, H-Index는 다음과 같이 구합니다.

어떤 과학자가 발표한 논문 n편 중, h번 이상 인용된 논문이 h편 이상이고 나머지 논문이 h번 이하 인용되었다면 h의 최댓값이 이 과학자의 H-Index입니다.

어떤 과학자가 발표한 논문의 인용 횟수를 담은 배열 citations가 매개변수로 주어질 때, 이 과학자의 H-Index를 return 하도록 solution 함수를 작성해주세요.


제한사항

과학자가 발표한 논문의 수는 1편 이상 1,000편 이하입니다.
논문별 인용 횟수는 0회 이상 10,000회 이하입니다.


문제 해결

  • 배열을 오름차순으로 정렬

  • h번 이상 인용된 논문의 수를 cnt_h라 정의했을때 h를 각 배열의 값들과 비교하여 cnt_h를 구하고 그때의 h값이 max_h값보다 클 경우 max_h = h

  • cnt_h 와 h가 같다면 return h

  • cnt_h가 h보다 작다면 return max_h

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int solution(vector<int> citations) {
    int answer = 0;
    int n = citations.size();
    int max_h = 0;
    int h = 0;
    
    sort(citations.begin(),citations.end());
    
    while(true){
        int cnt_h = 0;
        for(int i=0; i<n; i++){
            if(citations[i] >= h){ cnt_h++; }
        }
        if(cnt_h == h){ return h; }
        else if(h > cnt_h){ return max_h; }
        max_h = max(max_h, h);
        h++;
    }
    return answer;
}

피드백

다른 사람의 풀이

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int solution(vector<int> citations) {
    sort(citations.begin(), citations.end(), greater<int>());

    for (int i = 0; i < citations.size(); ++i) {
        if (citations[i] < i + 1) {
            return i;
        }
    }

    return citations.size();
}
  1. 배열을 내림차순으로 정렬
  2. 내가 썻던 h의 역할을 i+1로 대체

만약 [1000, 1000, 1000, 1000, 1000]이라 해도
for문을 다 돌고나서 if문에 걸러지지 않을 경우를 대비해서
return citations.size()를 사용

프로그래머스 - H-index

profile
백엔드 개발자 지망생

0개의 댓글