532. K-diff Pairs in an Array

本文介绍了一种使用HashSet解决寻找数组中k-diff对数量的方法。通过遍历数组并检查是否存在nums[i]-k或nums[i]+k的方式,有效避免了重复计数,最终返回不重复的k-diff对总数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers and an integerk, you need to find the number of unique k-diff pairs in the array. Here ak-diff pair is defined as an integer pair (i, j), where i and j are bothnumbers in the array and their absolute difference is k.

Example 1:

Input: [3, 1, 4, 1, 5], k = 2

Output: 2

Explanation: There are two 2-diff pairs inthe array, (1, 3) and (3, 5).

Although we have two 1s in the input, weshould only return the number of unique pairs.

Example 2:

Input:[1, 2, 3, 4, 5], k = 1

Output: 4

Explanation: There are four 1-diff pairs inthe array, (1, 2), (2, 3), (3, 4) and (4, 5).

Example 3:

Input: [1, 3, 1, 5, 4], k = 0

Output: 1

Explanation: There is one 0-diff pair inthe array, (1, 1).

翻译:给定一个整数数组和一个整数k,你需要找到数组中唯一的k-diff对的数量。 这里,k-diff对被定义为整数对(i,j),其中i和j都是数组中的数字,它们的绝对差是k。

示例1:

输入:[3,1,4,1,5],k = 2

输出:2

说明:阵列中有两个2-diff对,(1,3)和(3,5)。

虽然我们在输入中有两个1,但我们应该只返回唯一对的数量。

示例2:

输入:[1,2,3,4,5],k = 1

输出:4

说明:阵列中有四个1-diff对,(1,2),(2,3),(3,4)和(4,5)。

示例3:

输入:[1,3,1,5,4],k = 0

输出:1

说明:阵列中有一个0-diff对,(1,1)。

分析:这题利用Set集合来解决,解决的思想和巧妙,以前做的leetcode也用到过(用的map集合)。直接比较集合中是否存在nums[i]-k或者nums[i]+k,然后为了避免重复,将结果放到set中。代码如下:

public class Solution {

   public int findPairs(int[] nums, int k) {

       if(nums==null||k<0)  return 0;

           Set<Integer>set=new HashSet<Integer>();

           Set<Integer>setCount=new HashSet<Integer>();

           for(inti=0;i<nums.length;i++){

                 if(set.contains(nums[i]-k))setCount.add(nums[i]);

                 if(set.contains(nums[i]+k))setCount.add(nums[i]+k);

                 set.add(nums[i]);

           }

           returnsetCount.size();

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值