原题是:
Screen Shot 2017-11-22 at 12.14.12 PM.png思路是:
两指针。
要注意的是K为0,和为负数的corner case。
Python里list去重的方法,我经常使用:list(set(nums))
代码是:
class Solution:
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0 :
return 0
elif k != 0:
noDup = list(set(nums))
noDup = sorted(noDup)
cnt, i ,j = 0, 0, 1
while i < len(noDup) and j < len(noDup):
if noDup[j] - noDup[i] == k:
cnt += 1
i += 1
j += 1
elif noDup[j] - noDup[i] > k:
i += 1
else:
j += 1
else:
nums = sorted(nums)
candidate = []
cnt = 0
for i in range(len(nums)):
if i < len(nums)-1 and nums[i] == nums[i+1]:
candidate.append(nums[i])
cnt = len(list(set(candidate)))
return cnt
网友评论