leetcode532

Description:

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.

Note:

1.The pairs (i, j) and (j, i) count as the same pair.

2.The length of the array won't exceed 10,000.

3.All the integers in the given input belong to the range: [-1e7, 1e7].

Solution:

首先O(n^2)的算法无法通过本题,为了快速查找与每个数之差绝对值为k的数是否在数组中,可以考虑排序然后二分查找的方法,复杂度为O(nlogn)或者直接建立以数值为键,以出现次数为值建立字典,然后对字典每个键查找比它大k的数是否存在,因为一对数总有小有大,这样统计就不会重复,因为python的字典是hash table实现的,所以复杂度是O(n),这题还有2个坑,一个是k<0的情况,直接return 0,还有一个是k=0的情况,要查看字典每个键的值是否>1,若>1,答案加1,代码如下:

class Solution():
	def findPairs(self, nums, k):
		if k<0:
			return 0
		num2={
		}
		res=0
		n=len(nums)
		for number in nums:
			l=num2.get(number,0)
			num2[number]=l+1
		if k==0:
			for number in num2.keys():
				if num2[number]>1:
					res=res+1
		else:
			 for number in num2.keys():
				 if num2.get(number+k,0)>0:
					 res=res+1
		return res



首先
首先
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值