LeetCode 532. K-diff Pairs in an Array

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

二、输入输出

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.
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).
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

三、解题思路

  • 注意是绝对距离,是|i - j| 所以k < 0直接返回0。不要丢掉这种情况
  • 假设k!=0 那么可以把数存到set中,set是集合,里面的元素不会重复。依次遍历,并查看set(i) + k是否也在set中:在,计数器加1;不在,继续遍历
  • 对于k=0,同样借助set。在插入到set之前,首先判断是否已经包含该数字,如果有,说明出现了相同的数字,计数器加一。
  • 注意k=0时,<1,1>这是1种,如果输入是[1,1,1,1,1]那么应该输出是1,不是4。所以我们需要把出现过的相同的数记下来,遍历过程中如果再次出现,直接忽略,不在考虑
    int findPairs(vector<int>& nums, int k) {
        set<int> s;
        int n = nums.size(), ret = 0;
        if( k < 0 ){
            return 0;
        }
        else if( k == 0){
            set<int> searched;
            for (int i = 0; i < n; ++i) {
                if (s.find(nums[i]) != s.end() && searched.count(nums[i]) == 0) {
                    ret++;
                    searched.insert(nums[i]);
                }
                else
                    s.insert(nums[i]);
            }
        }else{
            for (int i = 0; i < n; ++i) {
                s.insert(nums[i]);
            }
            for (set<int>::iterator ite = s.begin(); ite != s.end(); ite++){
                if(s.find(*ite + k) != s.end())
                    ret++;
            }
        }
        return ret;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值