Advertisement
Alexxik

Untitled

Sep 17th, 2023 (edited)
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.61 KB | None | 0 0
  1. // MARK: - Дан отсортированный список и index. Надо найти k ближайших чисел к числу nums[index]
  2.  
  3. func findClosestElements(_ a: [Int], _ index: Int, _ k: Int) -> [Int] {
  4.  
  5.     if index > a.count-1 {return []}
  6.     let number = a[index]
  7.     var l = 0
  8.     var r = a.count-1
  9.    
  10.     while r-l+1 > k {
  11.         let absR = abs(number-a[r])
  12.         let absL = abs(number-a[l])
  13.        
  14.         if absR >= absL {
  15.             r -= 1
  16.         } else {
  17.             l += 1
  18.         }
  19.     }
  20.     return Array(a[l...r])
  21. }
  22.  
  23. findClosestElements([1, 2, 3, 4, 4, 4, 4, 5], 3, 3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement