Skip to content

Instantly share code, notes, and snippets.

@st0le
Created June 30, 2013 00:00
Show Gist options
  • Save st0le/5893201 to your computer and use it in GitHub Desktop.
Save st0le/5893201 to your computer and use it in GitHub Desktop.
Linear Algorithm for 2SUM on a sorted array.
// If Array was already sorted
// Complexity - O(n)
private int[] findPair_4(int[] A) {
int left = 0, right = A.length - 1;
while (left < right) {
int s = A[left] + A[right];
if (s == 0)
return new int[]{A[left], A[right]};
else if (s > 0)
right--;
else
left++;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment