It is better to unordered_map instead of map because it takes O(1) to search,insert and delete operations


#1

int Solution::diffPossible(const vector &A, int B) {
unordered_map<int,int> m;
for(int i=0;i<A.size();i++) {
if(m[A[i]]==0) {
m[A[i]]=1;
}
else {
m[A[i]]++;
}
}

for(int i=0;i<A.size();i++) {
    int key=A[i];
    if(B==0) {
        if(m[key]>1) {
            return 1;
        }
    }
    else {
        int a=key+B;
        int b=key-B;
        if(m.find(a)!=m.end()) {
            return 1;
        }
        if(m.find(b)!=m.end()) {
            return 1;
        }
    }
}

return 0;

}


#2

int a=key+B;
int b=key-B;
krishna_14 what’s the use of this condition?


#3

Because we have to check elements with difference B right , so we are finding two elements ( i.e a and b) with difference B.if there is any element we will return true .Hope you get this