O(n) solution to this problem


#1

int Solution::diffPossible(vector &A, int B) {
int i=0,j=0;
while(i<A.size() && j<A.size()){
if(A[j]-A[i]==B){
if(i==j){
j++;
}else{
return 1;
}
}
else if(A[j]-A[i]<B){
j++;
}
else if(A[j]-A[i]>B){
i++;
}
}
return 0;
}


#2

You can simplify that first block as follows:

int Solution::diffPossible(vector &amp;A, int B) {
    int i = 0, j = 0;
    while(i < A.size() && j < A.size()) {
        if(A[j] - A[i] == B && i != j) {
            return 1;
        } else if(A[j] - A[i] <= B) {
            j++;
        } else if(A[j] - A[i] < B) {
            i++;
        }
    }
    return 0;
}