func sortAges(_ ages: inout [Int]) {
guard !ages.isEmpty else { return }
let oldestAge: Int = 99
var timesOfAge = [Int]() // 统计每个年龄出现的次数
// 年龄允许的范围是 0~99
guard ages.allSatisfy({ $0 > 0}),
ages.allSatisfy({ $0 <= oldestAge})
else { return }
for _ in 0...oldestAge {
timesOfAge.append(0)
}
for i in 0..<ages.count {
let age = ages[i]
timesOfAge[age] += 1
}
var index = 0
for i in 0...oldestAge {
for _ in 0..<timesOfAge[i] {
ages[index] = i
index += 1
}
}
}
摘抄资料:《剑指offer》
网友评论