标签:and list array tps https 重复 需要 code where
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
标签:and list array tps https 重复 需要 code where
原文地址:https://www.cnblogs.com/whatyouthink/p/13302944.html