Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - Дан отсортированный список и index. Надо найти k ближайших чисел к числу nums[index]
- func findClosestElements(_ a: [Int], _ index: Int, _ k: Int) -> [Int] {
- if index > a.count-1 {return []}
- let number = a[index]
- var l = 0
- var r = a.count-1
- while r-l+1 > k {
- let absR = abs(number-a[r])
- let absL = abs(number-a[l])
- if absR >= absL {
- r -= 1
- } else {
- l += 1
- }
- }
- return Array(a[l...r])
- }
- findClosestElements([1, 2, 3, 4, 4, 4, 4, 5], 3, 3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement