Last active
August 29, 2015 14:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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