Two Difference | The Walking Dad
Given an sorted array and find two numbers in the array having difference equal to given number.
Your function should return indices of the two numbers.
If there are multiple pairs, just return any of them. Return [-1,-1] if no result can be found.
You may assume that the input array has no duplicates.
Given an sorted array and find two numbers in the array having difference equal to given number.
Your function should return indices of the two numbers.
If there are multiple pairs, just return any of them. Return [-1,-1] if no result can be found.
You may assume that the input array has no duplicates.
vector<int> two_dif(vector<int>& A, int target) { vector<int> ret(2, -1); int left = 0, right = 1; while (left < A.size() && right < A.size()) { if (left == right) { right++; continue; } int diff = A[right] - A[left]; if (diff == target) { ret[0] = left; ret[1] = right; break; } else if (diff < target) { right++; } else { left++; } } return ret; }Read full article from Two Difference | The Walking Dad