Swift solution - Two Pointers, HashMap


  • 0
    class Solution {
        func findPairs_TwoPointers(_ nums: [Int], _ k: Int) -> Int {
            let nums = nums.sorted()
            var result = 0
            var i = 0
            var j = 0
            
            while i < nums.count {
                j = max(j, i + 1)
                while j < nums.count && nums[j] - nums[i] < k {
                    j += 1
                }
                if j < nums.count && nums[j] - nums[i] == k {
                    result += 1
                }
                while i + 1 < nums.count && nums[i] == nums[i + 1] {
                    i += 1
                }
                i += 1
            }
            
            return result
        }
        
        func findPairs_HashMap(_ nums: [Int], _ k: Int) -> Int {
            if nums.count == 0 || k < 0 {
                return 0
            }
            
            var map = [Int: Int]()
            var count = 0
            
            for num in nums {
                if let value = map[num] {
                    map[num] = value + 1
                } else {
                    map[num] = 1
                }
            }
            for (key, value) in map {
                if k == 0 {
                    if value >= 2 {
                        count += 1
                    }
                } else {
                    if map.keys.contains(key + k) {
                        count += 1
                    }
                }
            }
            
            return count
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.