LC 532. K-diff Pairs in an Array

Nilanjan Deb · April 6, 2020

This is my CPP solution.

class Solution {
public:
    int findPairs(vector<int>& nums, int k) {
        int cnt = 0;
        sort(nums.begin(),nums.end());
        unordered_map<int,int> umap;
        if(k<0 || nums.size() < 2)
            return 0;
        if(!k){
            for(int i=0;i<nums.size()-1;i++){
                if(nums[i]==nums[i+1]){
                if(umap.find(nums[i]) == umap.end()){
                    umap[nums[i]] = nums[i] + k;
                    cnt++;
                }
                else
                    continue;
                }
            }
            return cnt;
        }
        for(int i=0;i<nums.size();i++){
            if(find(nums.begin(),nums.end(),nums[i]+k)!=nums.end()){
                if(umap.find(nums[i]) == umap.end()){
                    umap[nums[i]] = nums[i] + k;
                    cnt++;
                }
                else
                    continue;
            }
        }
        return cnt;
    }
};


Dicussion Forum