您的位置:首页 > 其它

LeetCode----15. 3Sum

2016-09-19 09:48 465 查看
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 the array which gives the sum of zero.

Note: 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]
]


Subscribe to see which companies asked this question

public class Solution {

public ArrayList<ArrayList<Integer>> threeSum(int[] num) {

ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
if(num == null || num.length < 3) {
return rst;
}
Arrays.sort(num);
for (int i = 0; i < num.length - 2; i++) {
if (i != 0 && num[i] == num[i - 1]) {
continue; // to skip duplicate numbers; e.g [0,0,0,0]
}

int left = i + 1;
int right = num.length - 1;
while (left < right) {
int sum = num[left] + num[right] + num[i];
if (sum == 0) {
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(num[i]);
tmp.add(num[left]);
tmp.add(num[right]);
rst.add(tmp);
left++;
right--;
while (left < right && num[left] == num[left - 1]) { // to skip duplicates
left++;
}
while (left < right && num[right] == num[right + 1]) { // to skip duplicates
right--;
}
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return rst;
}
}


Input:[-1,0,1,2,-1,-4]

Output:[[2,-1,-1]]

Expected:[[-1,-1,2],[-1,0,1]]

Input:[-1,0,1,2,-1,-4]

Output:[[-1,-1,2],[-1,0,1],[-1,0,1]]

Expected:[[-1,-1,2],[-1,0,1]]


//此方法时间超时
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {

ArrayList<List<Integer>> ls=new ArrayList<List<Integer>>();
if(nums.length<3){return ls;}
Arrays.sort(nums);
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
for(int k=j+1;k<nums.length;k++){
if(nums[i]+nums[j]+nums[k]==0){
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(nums[i]);list.add(nums[j]);list.add(nums[k]);
while(!ls.contains(list)){ls.add(list);}
}
}
}
}
return ls;
}
}//



Submission Result: Time Limit Exceeded  More
Details 

Last executed input:[4,-9,-13,-9,0,-12,12,-14,12,1,3,5,5,8,2,-2,8,1,2,-6,-6,1,6,-15,-2,7,-11,3,-2,1,11,10,8,14,8,-15,9,5,-14,6,14,-3,-12
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: