您的位置:首页 > 其它

LeetCode|3Sum

2013-11-12 08:35 197 查看
Note:

Elements in a triplet (a,b,c) must be in non-descending order. (ie, 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)

 

 

 

 

 

//Program Runtime: 728 milli secs
public class Solution {

public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
Arrays.sort(num);
int len = num.length;
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
HashSet<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();

for (int i = 0; i < len - 2; i++) {
int a = num[i];
int j = i + 1;
int k = len - 1;
while (j < k) {
int b = num[j];
int c = num[k];
if (a + b + c == 0) {
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(a);
list2.add(b);
list2.add(c);
set.add(list2);
j++;
k--;
}else if (a + b + c < 0) {
j++;
}else if (a + b + c > 0) {
k--;
}
}
}

Iterator<ArrayList<Integer>> it = set.iterator();
while (it.hasNext()) {
list.add(it.next());
}

return list;
}
}


这道虽然不是那么难,但是要注意的是边界条件的判断和代码的简洁;排序是个好东西。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息