LeetCode编程练习

来源:互联网 发布:淘宝店铺市场 编辑:程序博客网 时间:2024/06/07 02:25

参考链接:http://blog.csdn.net/zhouziyu2011/article/details/60466898

题目:

   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 theirabsolute difference is k.

         Example 1:

         Input: [3, 1, 4, 1, 5], k = 2         Output: 2         Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).        Although we have two 1s in the input, we should 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 in the 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 in the array, (1, 1).

       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].

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

       示例:输入[3,1,4,1,5],k = 2,输出2,数组中有两个2-diff对(1,3)和(3,5),虽然输入中有两个1,但只返回唯一对的数目。


思路:

   查看解决方案,定义哈希集,存储差值等于目标数的元素a以及出现过得值b,判断遍历的元素与目标元素的差值或者和在数组中是否存在,若存在则说明满足题目的条件。


     另一种写法,先对数组进行排序,用一个哈希值set存储出现过的值,用于后面判断某个元素是否已配对,当k不等于0时找出差的绝对值为k的对数,当k=0时则找出值相等的对数,用sameSet存储所有成对的值,避免同一个值加入多次。










原创粉丝点击