双指针 532. K-diff Pairs in an Array

来源:互联网 发布:python计算器源代码 编辑:程序博客网 时间:2024/06/10 14:32

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 = 2Output: 2Explanation: 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 = 1Output: 4Explanation: 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 = 0Output: 1Explanation: 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].
方法1:使用unordered_set和unordered_map
重复的数字不用考虑,操作和顺序没有关系(因为是边插入,边搜索,需要搜索一个值的两边,否则容易漏掉数值,因此不需要是有序的)。使用unordered_set存储找到的复合要求的pair的较小者。时间复杂度为O(n),空间复杂度为O(n)
class Solution {public:    int findPairs(vector<int>& nums, int k) {        unordered_set<int> starter;        unordered_map<int,int> indices;        if(k<0) return 0;//注意当k为0的情况        for(int i=0;i<nums.size();i++)        {            if(indices.count(nums[i]-k))            starter.insert(nums[i]-k);//只存储pair的较小值            if(indices.count(nums[i]+k))            starter.insert(nums[i]);            indices[nums[i]]++;        }        return starter.size();    }};
方法2:使用双指针思想
排好序之后,从头找满足要求的数。节省额外的空间,但是增加了时间复杂度。
class Solution {public:    int findPairs(vector<int>& nums, int k) {        int res=0,j=0;        sort(nums.begin(),nums.end());        int n=nums.size();        if(k<0||n<=1) return 0;        for(int i=0;i<n;i++)        {            j=max(j,i+1);            while(j<n&&nums[j]-nums[i]<k) j++;            if(j<n&&nums[j]-nums[i]==k) ++res;            while(i<n-1&&nums[i]==nums[i+1]) ++i;        }        return res;    }};



0 0
原创粉丝点击