【leetcode】532. K-diff Pairs in an Array(Python & C++)

来源:互联网 发布:南方周易软件安卓版 编辑:程序博客网 时间:2024/06/05 22:28

532. K-diff Pairs in an Array

题目链接

532.1 题目描述:

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:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won’t exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7].

532.2 解题思路:

  1. 思路一:分为k==0和k>0两种情况。设置计数器count=0,并最后返回count。首先对nums数组排序。

    • 当k==0时,利用map,每个元素与其数量相对应,遍历map,如果其数量大于1,则count++。返回count。
    • 当k>0时,循环数组nums,如果发现后一个元素与前一个元素相同,则continue,直到找到一个不同的数nums[i],然后进入内循环,从其后查找是否存在比其大k的数nums[j],如果存在,count++,并且break。如果nums[j]-nums[i]大于k,则直接break。最后返回count。
  2. 思路二:利用set和map。用set存放符合k-diff对中较小的那个数,利用set元素唯一的特点,最后直接返回set的大小即可。map用来存放nums数组中每个元素的数量。遍历nums数组,如果在map中存在nums[i]-k,则将nums[i]-k插入到set中;如果在map中存在nums[i]+k,则将nums[k]插入到set中;map[nums[i]]++。最后返回set大小即可。

以上两种对于C++对适用,但用Python实现时,均出现了超时,所以思路三、思路四是针对Python的方法。主要是利用Python中collection模块。

  1. 思路三:根据k的值分为三种情况,

    • 如果k小于0,直接返回0。
    • 如果k==0,直接返回collections.Counter(nums).values()中值大于1的个数。
    • 如果k>0,先将setset(nums)和set(v+k for v in nums)做交集,然后返回其长度即可。
  2. 思路四:类似思路三。首先获取c=collections.Counter(nums),遍历c,如果k>0且i+k也在c中,或者k==0且c[i]>1(表示个数大于1),则count++。最后返回count。

532.3 C++代码:

1、思路一代码(35ms):

class Solution126 {public:    int findPairs(vector<int>& nums, int k) {        if (nums.size() == 0)            return 0;        sort(nums.begin(), nums.end());        int count = 0;        if (k==0)        {            map<int,int>sum;            for (int i = 0; i < nums.size();i++)            {                sum[nums[i]]++;            }            map<int, int>::iterator it;            for (it = sum.begin(); it != sum.end(); it++)            {                if (it->second > 1)                    count++;            }            return count;        }        else        {            for (int i = 0; i < nums.size() - 1; i++)            {                if (nums[i + 1] == nums[i])                    continue;                for (int j = i + 1; j < nums.size(); j++)                {                    if (nums[j] - nums[i] == k)                    {                        count++;                        break;                    }                    if (nums[j] - nums[i] > k)                        break;                }            }            return count;        }    }};

2、思路二代码(43ms)

class Solution126_1 {public:    int findPairs(vector<int>& nums, int k) {        if (nums.size() == 0 || k<0)            return 0;        set<int>count;        map<int, int>value;        for (int i = 0; i < nums.size();i++)        {            if (value.count(nums[i] - k))                count.insert(nums[i] - k);            if (value.count(nums[i] + k))                count.insert(nums[i]);            value[nums[i]]++;        }        return count.size();    }};

532.4 Python代码:

1、思路一代码(超时)

class Solution(object):    def findPairs(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: int        """        if len(nums)==0 or k<0:            return 0        count=0        if k==0:            d={}            for i in range(len(nums)):                if nums[i] in d.keys():                    d[nums[i]]+=1                else:                    d[nums[i]]=1            for i in d:                if d[i]>1:                    count+=1            return count        else:            nums.sort()            for i in range(len(nums)-1):                if nums[i+1]==nums[i]:                    continue                for j in range(i+1,len(nums)):                    if nums[j]-nums[i]==k:                        count+=1                        break                    if nums[j]-nums[i]>k:                        break            return count

2、思路二代码(超时)

class Solution1(object):    def findPairs(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: int        """        if len(nums)==0 or k<0:            return 0        a=[]        b=[]        for i in range(len(nums)):            if nums[i]-k in a:                b.append(nums[i]-k)            if nums[i]+k in a:                b.append(nums[i])            a.append(nums[i])        return len(set(b))

3、思路三代码(85ms)

class Solution2(object):    def findPairs(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: int        """        if k==0:            return sum(v>1 for v in collections.Counter(nums).values())        elif k>0:            return len(set(nums)&set(v+k for v in nums))        else:            return 0

4、思路四代码(88ms)

class Solution3(object):    def findPairs(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: int        """        count=0        c=collections.Counter(nums)        for i in c:            if (k>0 and i+k in c) or (k==0 and c[i]>1):                count+=1        return count

原创粉丝点击