题目描述:找到数组中恰好差k的一对数,且不重复计算
思路:
1、第一种思路是我第一个看懂的,还是使用dictionary这种数据结构。把每种数据存在dict中,当k=0的时候,查找dict中是否有value大于1的关键字,若有则rec+1,;如果k>1, 则遍历dict,若key+k in dict 则rec+1(不是很明白为什么k一定要大于0)
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
dic = {}
rec = 0
for i in nums:
dic[i] = 1 if i not in dic else dic[i] + 1
for key in dic:
if (k == 0 and dic[key]>1) or (k > 0 and (key+k in dic)):
rec += 1
return rec
2、排序加滑动窗口遍历
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
left=0
right = 1
nums.sort()
rec = 0
while right < len(nums):
firnum = nums[left]
curnum = nums[right]
if curnum - firnum < k:
right += 1
elif k < curnum - firnum:
left += 1
else:
rec += 1
while left<len(nums) and nums[left]==firnum:
left += 1
while right < len(nums) and nums[right] == curnum:
right += 1
if left == right:
right += 1
return rec
小结:做一个问题之前,要把注意的点写出来,比如说临界点,还有就是有什么条件是需要注意的。