본문 바로가기
#알고리즘 [Algorithm]/Problem

[HackerRank] Climbing the Leaderboard

by cy_mos 2022. 2. 17.
반응형
카테고리 게시글 작성 날짜 게시글 최근 수정 날짜 작성자
Algorithm 2022.02.17. 23:33 2022.02.17. 23:33 Dev.Yang

 

An arcade game player wants to climb to the top of the leaderboard and track their ranking. The game uses Dense Ranking, so its leaderboard works like this: 

  • The player with the highest score is ranked number  on the leaderboard. 
  • Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.

 

[Function Description]

Complete the climbingLeaderboard function in the editor below. 

climbingLeaderboard has the following parameter(s): 

  • int ranked[n]: the leaderboard scores 
  • int player[m]: the player's scores 

 

[Returns]

  • int[m]: the player's rank after each new score

🛠 Climbing the Leaderboard With Swift Source Code

import Foundation

func findIndex(ranked: [Int], score: Int, first: Int, last: Int) -> Int {
    
    let halfIndex = (first + last) / 2
    
    if first > last { return halfIndex }
    
    if ranked[halfIndex] == score {
        return halfIndex
    }
    else if ranked[halfIndex] < score {
        return findIndex(ranked: ranked, score: score, first: first, last: halfIndex - 1)
    }
    else {
        return findIndex(ranked: ranked, score: score, first: halfIndex + 1, last: last)
    }
}

/*
 * Complete the 'climbingLeaderboard' function below.
 *
 * The function is expected to return an INTEGER_ARRAY.
 * The function accepts following parameters:
 *  1. INTEGER_ARRAY ranked
 *  2. INTEGER_ARRAY player
 */

func climbingLeaderboard(ranked: [Int], player: [Int]) -> [Int] {

    var answer: [Int] = []
    
    var rank: Int = Int.zero
    var leaderboard: [Int: Int] = [:]
    for score in ranked {
        if leaderboard.keys.contains(score) == false { rank = rank + 1 }
        
        leaderboard.updateValue(rank, forKey: score)
    }
    
    let length: Int = ranked.count
    for score in player {
        // 동일 한 점수를 가진 사용자가 있는 경우에는 Dictionary에서 값을 가져옵니다.
        if let rank = leaderboard[score] {
            answer.append(rank)
            continue
        }
        
        let index = findIndex(ranked: ranked, score: score, first: Int.zero, last: length - 1)
        
        let approach = ranked[index]
        if let rank = leaderboard[approach] {
            answer.append(approach > score ? rank + 1 : rank)
        }
    }
    
    return answer
}

🚀 REFERENCE

반응형

댓글