532. K-diff Pairs in an Array

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

 给一个数组,问有多少不重复的pair(i,j),使得i和j的绝对值差等于k

这个题有挺多坑的。k=0的时候需要判断下同一个数是否出现了2次,k小于0的时候,直接给0,巨恶心k居然还能小于0

hashtable搞一下就行。注意边界条件

class Solution(object):
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        d = {}
        ans = 0
        for value in nums:
            if value in d:
                d[value] += 1
            else:
                d[value] = 1
        for key,value in d.items():
            if key + k in d:
                if k == 0:
                    ans += 1 if d[key + k] >= 2 else 0
                elif k > 0:
                    ans += 1
        return ans

 

posted @ 2020-07-14 22:56  whatyouthink  阅读(167)  评论(0编辑  收藏  举报