Leetcode532. 找出数组中绝对值为k的数值对的数目

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

Example1:
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.

Example2:
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).

Example3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

解题分析

题目乍一看,给我的第一思路就是要消除数组中重复的元素;因为题目明确说了,相同的元素只算一次。

接下来我们来考虑怎样统计数组中绝对值为k的数值对的数目。我们可以这样想,用另外一个数组来存储每个元素对应的数值对的值。而我们知道绝对值为k的数字有两个,即k和-k。因此,在前面消除数组重复元素的时候,对数组从小到大进行排序,这样可以只考虑一种情况而减少重复工作。
在遍历数组元素的时候,我们先判断在另一个数组中有没有该数组元素,如果有,说明就找到了一个数值对;然后再把该元素对应的数值对的值(即该元素的值+k)存进数组中。这样当数组遍历完之后,数目的计算就完成了。

但是这里还有一个细节问题容易忽略,就是k=0的情况。前面我们消除了数组的重复元素,因此此时数组中没有任何一个重复元素,如果我们按照上面的做法,最后的结果就始终为0。所以,在消除数组重复元素之前,我们需要用unordered_map哈希表来统计每个元素出现的次数,如果次数大于1,数值对的数目就加1,这样所有的问题就解决了。

源代码

class Solution {
public:
    int findPairs(vector<int>& nums, int k) {
        int pair = 0, size = nums.size(), i;
        unordered_map<int, int> map;
        for (i = 0; i < size; i++) {
            map[nums[i]]++;
        }
        sort(nums.begin(), nums.end());
        vector<int>::iterator end_unique = unique(nums.begin(), nums.end());
        nums.erase(end_unique, nums.end());
        if (k == 0) {
            for (i = 0; i < nums.size(); i++) {
                if (map[nums[i]] > 1) {
                    pair++;
                }
            }
        }
        else if (k > 0) {
            vector<int> add;
            for (i = 0; i < nums.size(); i++) {
                vector<int>::iterator it_add = find(add.begin(), add.end(), nums[i]);
                if (it_add != add.end()) {
                    pair++;
                }
                add.push_back(nums[i] + k);
            }
        }
        return pair;
    }
};

这只是我对这道题的一些想法,有问题还请在评论区讨论留言~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值