Algorithm/프로그래머스

[프로그래머스 level2] H-index (C++)

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

위 말을 이해하기가 어려울 수 있다.

h번 이상 인용된 논문이 h편 이상이다 -> 이 문장의 뜻은 h는 과학자가 발표한 논문의 개수 이하가 될 것이다.

 

예시를 보면서 이해해 보자.

논문의 인용 횟수 [3, 0, 6, 1, 5] 가 주어진다.

 

먼저 논문을 오름차순 정렬한다.

[0, 1, 3, 5, 6] 

 

여기서 2회 이상 인용된 논문은 3, 5, 6 논문이 되고, 2회 이하 인용된 논문은 0, 1 논문이 된다.

3회 이상 인용된 논문은 3, 5, 6 논문이 되고, 3회 이하 인용된 논문은 0, 1, 3 논문이 된다.

 

배열이 정렬 되었기 때문에 lower_bound와 upper_bound를 사용하면 인용 횟수가 i번 이상인 논문의 개수를 알 수 있다.

 

인용 횟수가 i번 이상인 논문 up

int up = citations.size() - (lower_bound(citations.begin(), citations.end(), i) - citations.begin());

 

인용 횟수가 i번 이하인 논문 down

int down = upper_bound(citations.begin(), citations.end(), i) - citations.begin();

 

실제 답을 구하는 조건문

if(up >= i && down <= i){
    answer = i;
}

 

up회 이상 인용된 논문의 개수는 i 이상이어야 한다 == h번 이상 인용된 논문이 h편 이상이어야 한다.

 

 

 

 

최종 코드

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

using namespace std;

int solution(vector<int> citations) {
    int answer = 0;
    sort(citations.begin(), citations.end());
    
    for(int i = 0; i <= citations.size(); i++){
        int up = citations.size() - (lower_bound(citations.begin(), citations.end(), i) - citations.begin());
        int down = upper_bound(citations.begin(), citations.end(), i) - citations.begin();
        if(up >= i && down <= i){
            answer = i;
        }
    }
    
    
    return answer;
}