H-index

bird.j·2021년 10월 12일
0

프로그래머스

목록 보기
45/53

프로그래머스

이 문제는 은근히 말이 헷갈렸다.
그런데 문제에서 나온 설명 그대로 코드로 작성하면 된다.

def solution(citations):
    citations.sort(reverse=True)
    
    for h in range(0, max(citations)+1):
        cnt = 0
        for i in range(len(citations)):
            if citations[i] >= h:
                cnt += 1
        if cnt <= h:
            return h
    return 0

처음에 이런식으로 구현하니 11번 테스트케이스에서 통과를 못했다.
[0, 1, 1] 일 때 답이 1이 나와야하는데 1이상인 수가 2개이다보니 if조건을 충족시키지 못해 0을 출력하는 것이었다.
그래서 h를 큰 수에서부터 비교하는 걸로 바꿨더니 잘 통과되었다.
또한 주의할 점은 h를 min(citations)로 시작하는 것이 아니라 0부터 시작해야하는 점이다.

def solution(citations):
    citations.sort(reverse=True)
    
    for h in range(max(citations), -1, -1):
        cnt = 0
        for i in range(len(citations)):
            if citations[i] >= h:
                cnt += 1
        if cnt >= h:
            return h 
    return 0


다른 방법들
def solution(citations):
    citations.sort()
    
    n = len(citations)
    for i, v in enumerate(citations):
        if v >= n-i:
            return n-i
    return 0

우선 citations를 오름차순으로 정렬한다.
citations = [0, 1, 3, 5, 6]

각각의 인덱스와 값에 대해서 값이 n-i보다 크거나 같아지는 첫번째 n-i를 바로 리턴한다.

다르게 푸는 방법도 있는데 정말 경이로운 방식이었다..

def solution(citations):
    citations.sort(reverse=True)
    answer = max(map(min, enumerate(citations, start=1)))
    return answer

0개의 댓글