Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - 2006. Count Number of Pairs With Absolute Difference K
- // Решение 1
- func countKDifferenceOne(_ nums: [Int], _ k: Int) -> Int {
- var total = 0
- var dict = [Int:Int]()
- for value in nums {
- dict[value, default: 0] += 1
- }
- for value in nums {
- let diff = value - k
- if dict[diff] != nil {
- total += dict[diff]!
- }
- }
- return total
- }
- countKDifferenceOne([1,2,2,1], 1)
- // Решение 2
- func countKDifferenceTwo(_ nums: [Int], _ k: Int) -> Int {
- var total = 0
- var dict = [Int:Int]()
- for x in nums {
- total += (dict[x - k] ?? 0) + (dict[x + k] ?? 0)
- dict[x, default: 0] += 1
- }
- return total
- }
- countKDifferenceTwo([1,3], 3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement