LintCode 1187: K-diff Pairs in an Array (同向双指针)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/roufoo/article/details/85522981
  1. K-diff Pairs in an Array
    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
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).
Notice
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].

思路:同向双指针。记得先排序。
注意:
1)感觉好像两个数之和等于某个固定数就用反向双指针。
如果两个数之差等于某个固定数就用同向双指针。

代码如下:

class Solution {
public:
    /**
     * @param nums: an array of integers
     * @param k: an integer
     * @return: the number of unique k-diff pairs
     */
    int findPairs(vector<int> &nums, int k) {
        
        int result = 0;
        int len = nums.size();
        if (len <= 1) return 0;
        
        sort(nums.begin(),  nums.end());
        int p1 = 0, p2 = 1; // p2 is ahead of p1
        set<pair<int, int>> s;
        if (k < 0) k = -k;  //important!
        
        while(p1 < p2) {
            int diff = nums[p2] - nums[p1]; 
            if (diff == k) {
                s.insert(make_pair(min(nums[p1], nums[p2]), max(nums[p1], nums[p2])));
                p1++; p2++;
            } else if (diff < k) {
                p2++;
            } else {
                p1++;
            }
        }
        
        return s.size();
    }
};

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/85522981