Skip to content

Instantly share code, notes, and snippets.

@alexnikol
Last active July 13, 2020 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexnikol/37d74c90c135300a51a212de7d1860d0 to your computer and use it in GitHub Desktop.
Save alexnikol/37d74c90c135300a51a212de7d1860d0 to your computer and use it in GitHub Desktop.
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