본문 바로가기

Leetcode

[Leetcode]_274. H-Index

문제

https://leetcode.com/problems/h-index/description/?envType=study-plan-v2&envId=top-interview-150 

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

풀이

위 문제에서 정수형 배열이 주어지고, 배열의 요소는 논문이 인용된 횟수를 나타내며 배열의 총 길이는 논문의 갯수를 의미한다.

H-Index는 h번 인용된 논문의 갯수가 h개 이상인 값 중 최댓값을 의미한다.

 

def hIndex(citations):
    curr = 0
    while True:
        count = 0
        for i in range(len(citations)):
            if citations[i] > curr:
                count += 1
        if count > curr:
            curr += 1
        else:
            break
    
    return curr
  • curr 변수는 최대값인 h를 의미하고 초기값은 0회 인용부터 시작한다.
    • 왜냐하면, citations = [0] 인 경우, 반환값은 0이 되어야 하기 때문이다.
  • citations 배열을 순회하면서 curr 보다 citations의 요소값이 큰 경우 count 변수에 1씩 추가한다.
  • citations 배열 순회가 끝나고 count 변수가 curr(현재 최대값h)보다 크면 curr에 1을 추가한다.
    • count 변수가 curr 변수보다 작거나 같으면 반복문을 종료하고 curr 변수를 반환한다.