[programmers] H-Index

wonyu·2021년 12월 15일
0

algorithm

목록 보기
10/25

문제 링크

https://programmers.co.kr/learn/courses/30/lessons/42747

풀이 방법

처음에는 for문을 돌며 각 요소를 확인하여 citations[i]번 이상 인용된 게 citations[i]개 이상, 나머지는 citations[i]개 이하인지 확인하고자 했으나 무조건 citations 내에 있는 값에서 답을 찾는 게 아니라는 걸 알게 되었다.

이후 h를 가능한 가장 큰 값으로 초기화 한 뒤 문제에 나와있는 조건을 만족하는 논문 개수를 while문을 통해 카운트 하고 if문에서 조건을 만족하지 못하면 h값을 1씩 줄이는 방식으로 코드를 수정해서 통과했다.

좀 더 나은 방법이 있을 것 같다는 생각이 들어서 다른 사람들의 풀이를 참고하여 두 번째 코드를 작성했다.

코드

첫 통과 코드

def solution(citations):
    answer = 0
    citations = sorted(citations, reverse=True)
    # 처음엔 h값을 citations의 최댓값으로 초기화했으나 개수를 따져야 하므로 len(citations) 이상의 답이 나오는 것은 불가능
    h = len(citations)
    while h > 0:
        cnt, idx = 0, 0
        # h번 이상 인용된 논문 카운트
        while idx < len(citations) and citations[idx] >= h:
            cnt += 1
            idx += 1
        # 카운트한 논문 개수가 h 이상이고 나머지 논문이 h개 이하인지 확인
        if cnt >= h and len(citations) - cnt <= h:
            answer = h
            break
        else:
            h -= 1
    return answer

수정한 코드

def solution(citations):
    answer = 0
    citations = sorted(citations, reverse=True)
    length = len(citations)
    # 최댓값인 len(citations)부터 1씩 줄여가며 h값 검사
    # i는 확인할 h값. i-1은 citations의 인덱스.
    for i in range(length, 0, -1):
    	# 해당 위치의 값이 h보다 크다는 것은 h번 이상 인용된 논문이 h개 이상 존재한다는 뜻
        if citations[i - 1] >= i:
            answer = i
            break
    return answer

0개의 댓글