I found a 3Sum problem at http://www.leetcode.com/onlinejudge that looks like this:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in an array that gives the sum of zero.
Note: Elements in the triplet (a, b, c) must be in descending order. (i.e. a ≤ b ≤ c) The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
I went through the site and found this proposed solution:
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
Arrays.sort(num);
HashSet<ArrayList<Integer>> lstSoln = new HashSet<ArrayList<Integer>>();
ArrayList<Integer> tempArr = null;
for (int i = 0; i < num.length; i++) {
int j = i + 1;
int k = num.length - 1;
while (j < k) {
int sum3 = num[i] + num[j] + num[k];
if (sum3 < 0) {
j++;
} else if (sum3 > 0) {
k--;
} else {
tempArr = new ArrayList<Integer>();
Collections.addAll(tempArr, num[i], num[j], num[k]);
lstSoln.add(tempArr);
j++;
k--;
}
}
}
return new ArrayList<ArrayList<Integer>>(lstSoln);
}
, , . , , , , , , 0. for
if (num[i] > 0)
break;
for , , , . , if(). , COUNTER , .
, , , , , ! , ?