Algorithm/Programmers

[프로그래머스] h-index

메린지 2024. 4. 11. 16:53

1. 문제

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

2. 풀이

 

## 내 code ##

 

1) 내림차순 정렬한다
2) 시작은 제일 큰 citation
3) hindex가 0까지 돌리면서 hindex가 ciations[i] 보다 커지는 순간을 찾는다 ==> 이때 만약 hindex보다 그 citations[i]까지의 길이가 더 길거나 같으면 최대 hindex임
4) 근데 hindex 가 citations 안에 있는 수들보다 작을 수도 있으니 지나치면 -1씩 하면서 전체 길이가 hindex보다 커지는 순간을 찾는다.
def solution(citations):
    citations = sorted(citations, reverse=True)
    hindex = citations[0]
    
    while hindex > -1:
        if hindex > citations[-1]:
            for i in range(len(citations)):
                if hindex > citations[i]:
                    if hindex <= len(citations[0:i]):
                        return hindex
                    else:
                        break
        else:
            if hindex <= len(citations):
                return hindex            
        hindex -= 1
    return hindex

 

 

## 다른 code ##

def solution(citations):
    citations = sorted(citations)
    l = len(citations)
    for i in range(l):
        if citations[i] >= l-i:
            return l-i
    return 0

 

이건 다른분 코드인데 너무 잘짠거 같아서 들고 왓다.

 

나랑 반대로 오름차순 정렬하고, citations[i] 가 처음으로 남은 길이보다 크거나 같을때 리턴하는데, 이 l-i 는 전체에서 현재까지 리스트를 제거한 길이라고 생각하면, 갈수록 l - i 는 더 작아지니까 처음 작거나 같은게 max인 순간이다.