python solution with comments, O(n) time with 90%, use only one set for most of cases


  • 0
    P
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k < 0:
            return 0
        elif k == 0:
            # the zero set defined only when k is 0 that mark the same number only count once
            zero = set()        
    
        # add visited number in set for further comparison 
        visited = set(); cnt = 0
        for number in nums:
            if k != 0:
                if number not in visited:
                    if number + k in visited:
                        cnt += 1
                    if number - k in visited:
                        cnt += 1
                    visited.add(number)
            else:                
                if number in visited and number not in zero:
                    cnt += 1
                    zero.add(number)
                else:
                    visited.add(number)
        return cnt

Log in to reply
 

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