class Solution {
fun solution(citations: IntArray): Int {
// 인용 횟수를 내림차순으로 정렬
val sortedCitations = citations.sortedDescending()
// H-Index를 찾기 위한 변수
var hIndex = 0
// 정렬된 배열을 순회하면서 조건에 맞는 최대 h를 찾음
for (i in sortedCitations.indices) {
if (sortedCitations[i] >= i + 1) {
hIndex = i + 1
} else {
break
}
}
return hIndex
}
}
코드 설명
- 정렬 (sortedDescending)
- 주어진 citations 배열을 내림차순으로 정렬합니다.
- 예를 들어, [3, 0, 6, 1, 5] → [6, 5, 3, 1, 0].
- 조건 검사
- 논문의 순위를 i + 1로 계산합니다.
- 인용 횟수 sortedCitations[i]가 순위 i + 1 이상일 때, 해당 논문 수만큼의 H-Index를 만족합니다.
- 그렇지 않으면 반복문을 종료합니다.
- 최대 h값 저장
- 조건을 만족하는 최대 hIndex 값을 업데이트합니다.
로직 예제
citations = [3, 0, 6, 1, 5] 일 경우에
- 정렬하면 : [6, 5, 3, 1, 0]
- H-Index 계산:
- i = 0, citations[0] = 6, h = 1 → 조건 만족
- i = 2, citations[2] = 3, h = 3 → 조건 만족
- i = 3, citations[3] = 1, h = 4 → 조건 불만족 → 종료
- i = 1, citations[1] = 5, h = 2 → 조건 만족
- 결과: hIndex = 3
'코딩테스트 준비(kotlin) > 정렬' 카테고리의 다른 글
[프로그래머스] 가장 큰 수 (with kotlin) (0) | 2025.01.10 |
---|