Last active
July 13, 2020 18:00
-
-
Save alexnikol/37d74c90c135300a51a212de7d1860d0 to your computer and use it in GitHub Desktop.
Climbing the Leaderboard HackerRank - Medium Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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