public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>> ();
ArrayList<Integer> temp = new ArrayList<Integer> ();
if (num==null) return null;
int i, j, p, i_val=Integer.MAX_VALUE, j_val, p_val, sum;
Arrays.sort(num);
for (i=0; i<num.length-2; i++) {
if (num[i]==i_val) continue;
i_val = num[i];
j = i+1;
p = num.length-1;
while (j<p) {
sum = num[i]+num[j]+num[p];
j_val = num[j];
p_val = num[p];
if (sum==0) {
temp.clear();
temp.add(num[i]);
temp.add(num[j]);
temp.add(num[p]);
res.add((ArrayList<Integer>) temp.clone());
while (++j<p && num[j]==j_val);
} else if (sum>0) {
while (j<--p && num[p]==p_val);
} else {
while (++j<p && num[j]==j_val);
}
}
}
return res;
}
}
没有评论:
发表评论