首页 > 其他 > 详细

[Leetcode]532. K-diff Pairs in an Array

时间:2017-10-24 14:00:27      阅读:213      评论:0      收藏:0      [点我收藏+]

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.

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]

思路:先把数组按小到大排序。设当前的数为 p,判断 p 后面的数减去 p是否有等于 k 的,如果有等于k的,就增加k-diff-pair然后break(因为不能重复统计),

   eg :[1,2,3,3],k=2; 到下标为 2 时,已经满足条件,就不用进行了,否则下个数还是3,这样就重复统计了。

     令p = p下一个数。如此重复,知道p到最后一个数。

     此外,我还设置了一个前驱pre等于当前数p,等p递增后,判断p是否等于pre,如果等于,则continue;(这么做也是为了不重复统计)

   eg:[1,1,2,3],k=2;

class Solution {
    public int findPairs(int[] nums, int k) {
        if(nums.length==1)
            return 0;                       //如果这有一个数,返回0;
        int kDiffPair = 0;               //统计满足条件的且不重复的有多少对
        int pre = 0;        
Arrays.sort(nums);
for (int i=0;i<nums.length-1;i++){ if (i!=0&&nums[i]==pre) continue; // 如果是数组里第一个数,则前面肯定不会有重复的; for (int j = i+1;j<nums.length;j++){ if (nums[j]-nums[i]==k){ kDiffPair++; break; }
} pre
= nums[i]; //让pre等于当前的数,为了下一轮循环判断下个数是否等于pre } return kDiffPair; } }

 

[Leetcode]532. K-diff Pairs in an Array

原文:http://www.cnblogs.com/David-Lin/p/7722964.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!