C++ soln by binary search and by two pointer method(Easy to understand)


#1

Binary Search Method

int Solution::diffPossible(vector<int> &A, int B) {
int n = A.size();
sort(A.begin(),A.end());        // Sorting the for binary search

for(int i=0;i<n;i++){
    int x = B+A[i];             
    int j=i+1,k=n-1;
    while(j<=k){                // Searching for the no. which makes the different B
        int mid = (j+k)/2;
        if(A[mid] == x)
        return 1;               // if get the desire value then return 1
        else if(x>A[mid])       // if not and then search further accordingly
        j=mid+1;
        else
        k=mid-1;
    }
}    
return 0;
}

two-pointers method

int Solution::diffPossible(vector<int> &A, int B) {
int n = A.size();
sort(A.begin(),A.end());        

int i =0,j=1;
while(i<n && j<n){
    if(i == j){
        j++;
        continue;
    }
    if(A[j]-A[i] == B)
    return 1;
    else if(A[j]-A[i] < B)
    j++;
    else
    i++;
}
return 0;
}