Skip to content

Instantly share code, notes, and snippets.

@alexnikol
Last active Jul 13, 2020
Embed
What would you like to do?
Climbing the Leaderboard HackerRank - Medium Problem
func climbingLeaderboard(scores: [Int], alice: [Int]) -> [Int] {
func findClosestNumberInBoard(forNumber number: Int) -> Int { //Functions for searching the closest score in table
var left = 0 //with binary search
var right = scores.count - 1
var mid = 0
while left <= right {
mid = (left + right) / 2
if number == scores[mid] {
return scores[mid]
} else if number >= scores[mid] {
right = mid - 1
} else {
left = mid + 1
}
}
return scores[mid]
}
var result: [Int] = []
var places: [Int: Int] = [:] //Convert scores into places
var place = 1
for i in 0..<scores.count {
if places[scores[i]] == nil {
places[scores[i]] = place
place += 1
}
}
for aliceNumber in alice {
let number = findClosestNumberInBoard(forNumber: aliceNumber)
let placeForClosestNumber = places[number] ?? 0
var alicePlace = 0
if number > aliceNumber {
alicePlace = placeForClosestNumber + 1
} else {
alicePlace = placeForClosestNumber
}
result.append(alicePlace)
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment