数组中差为K的对数/K-diff Pairs in an Array(C++)

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

Answer:

class Solution {
public:
    int findPairs(vector<int>& nums, int k) {
        if(nums.size() < 2)
            return 0;
         //之前用map比较耗时
        /*map<int, int> mp;
        for(auto i : nums){
            if(mp.find(i) == mp.end()){
                mp.insert(make_pair(i,1));
            }
            else{
                ++mp.find(i)->second;
            }
        }*/
        int count = 0;
        vector<int> temp = nums;
        sort(temp.begin(), temp.end());
        if(k < 0)
            return 0;
        if(k==0) {
            for(int i=0;i<temp.size()-1;i++)
                //若数组下标为0且与下标为1的相等或者下标为i与i+1相等但i和i-1不等(避免重复计数eg:1,1,1)
                if(temp[i]==temp[i+1]&&(i==0||temp[i]!=temp[i-1])){
                    ++count;
                }
            return count;
        }
        /*for(auto beg = mp.begin(); beg != mp.end(); ++beg){
            temp.push_back(beg->first);
        }*/
        for(int i = 0; i < temp.size()-1; ++i){
            if(temp[i] != temp[i+1]){
                //binary_search:binary_search(data, data + N, key);查找范围:从data数组的第一个元素到第N-1个元素;如果找到key,返回true;没有找到,返回false.常用于查找元素是否存在.
                if(binary_search(temp.begin(), temp.end(), temp[i]+k))
                    ++count;
            }
        }
        return count;
        
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值