Skip to content

Instantly share code, notes, and snippets.

@alexandervasyuk
Last active August 29, 2015 14:07
Show Gist options
  • Save alexandervasyuk/a28a6972e193265a4159 to your computer and use it in GitHub Desktop.
Save alexandervasyuk/a28a6972e193265a4159 to your computer and use it in GitHub Desktop.
Given an integer array, output all pairs that sum up to a value k
public static List<Pair> pairsThatSumUpToK(int[] a, int k) {
Arrays.sort(a);
List<Pair> result = new ArrayList<Pair>();
int left = 0;
int right = a.length-1;
while(left < right) {
int sum = a[left] + a[right];
if (sum < k) left++;
else if (sum > k) right--;
else {
result.add(new Pair(a[left], a[right]));
left++;
right--;
}
}
return result;
}
public class Pair{
protected int x;
protected int y;
public class Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment