https://leetcode-cn.com/problems/k-diff-pairs-in-an-array/submissions/
我的答案
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
if k<0:
return 0
s=set(nums)
if k==0:
count=0
for i in s:
if nums.count(i)>=2:
count+=1
return count
res=set()
for i in sorted(s):
if i+k in s:
res.add(i)
return len(res)
可以点击到的最佳答案
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
res = 0
if k < 0: return 0
elif k == 0:
count = collections.Counter(nums)
for n, v in count.items():
if v >= 2:
res += 1
return res
else:
nums = set(nums)
for num in nums:
if num + k in nums:
res += 1
return res
所以他这里比我快的点就是他的collections.counter(nums)
用这个可以直接得到一个哈希表所以后面的调用就是count.items()