Advertisement
Alexxik

Untitled

Sep 18th, 2023
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.75 KB | None | 0 0
  1. // MARK: - 2006. Count Number of Pairs With Absolute Difference K
  2.  
  3. // Решение 1
  4. func countKDifferenceOne(_ nums: [Int], _ k: Int) -> Int {
  5.     var total = 0
  6.     var dict = [Int:Int]()
  7.     for value in nums {
  8.         dict[value, default: 0] += 1
  9.     }
  10.  
  11.     for value in nums {
  12.         let diff = value - k
  13.         if dict[diff] != nil {
  14.             total += dict[diff]!
  15.         }
  16.     }
  17.     return total
  18. }
  19. countKDifferenceOne([1,2,2,1], 1)
  20.  
  21. // Решение 2
  22. func countKDifferenceTwo(_ nums: [Int], _ k: Int) -> Int {
  23.     var total = 0
  24.     var dict = [Int:Int]()
  25.     for x in nums {
  26.         total += (dict[x - k] ?? 0) + (dict[x + k] ?? 0)
  27.         dict[x, default: 0] += 1
  28.     }
  29.     return total
  30. }
  31.  
  32. countKDifferenceTwo([1,3], 3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement