使用3层for循环暴力之
public class Solution {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> countList = new ArrayList<List<Integer>>();
List<Integer> list = null;
int length = nums.length;
for(int i = 0;i<length;i++){
for(int j = i+1;j<length;j++){
for(int k = j+1;k<length;k++){
if(nums[i]+nums[j]+nums[k]==0){
list = new ArrayList<Integer>();
int[] nu = new int[3];
nu[0] = nums[i];
nu[1] = nums[j];
nu[2] = nums[k];
Arrays.sort(nu);
list.add(nu[0]);
list.add(nu[1]);
list.add(nu[2]);
if(!countList.contains(list)){
countList.add(list);
}
}
}
}
}
return countList;
}
public static void main(String[] args){
int[] nums = {-1,0,1,2,-1,-4};
List<List<Integer>> countList = threeSum(nums);
System.out.println(countList.size());
for(int i = 0;i < countList.size();i++){
System.out.println(countList.get(i));
}
}
}
当输入参数为[13,14,1,2,-11,-11,-1,5,-1,-11,-9,-12,5,-3,-7,-4,-12,-9,8,-13,-8,2,-6,8,11,7,7,-6,8,-9,0,6,13,-14,-15,9,12,-9,-9,-4,-4,-3,-9,-14,9,-8,-11,13,-10,13,-15,-11,0,-14,5,-4,0,-3,-3,-7,-4,12,14,-14,5,7,10,-5,13,-14,-2,-6,-9,5,-12,7,4,-8,5,1,-10,-3,5,6,-9,-5,9,6,0,14,-15,11,11,6,4,-6,-10,-1,4,-11,-8,-13,-10,-2,-1,-7,-9,10,-7,3,-4,-2,8,-13]
超时,没有想到更好的办法。
百度后,发现对数组进行递增排序,此时不需要对得到的结果集合进行递增排序,得到的结果集即为递增排序集合,节省了对结果集进行排序的时间
public class Solution {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> countList = new ArrayList<List<Integer>>();
List<Integer> list = null;
int length = nums.length;
//对数组进行排序
Arrays.sort(nums);
for(int i = 0;i<length-2;i++){
//nums[i]=nums[i-1]
if(i >0 && nums[i] == nums[i-1]){
continue;
}
int p = i+1;
int q= length-1;
while(p<q){
//p!=q是为了避免nums[p]和nums[q]为相同索引下的值
if(nums[i]+nums[p]+nums[q]==0&&p!=q){
list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[p]);
list.add(nums[q]);
countList.add(list);
//nums[p] == nums[p+1]避免结果集重复
while(p<q&&nums[p] == nums[p+1]){
p++;
}
//nums[q]==nums[q-1]避免结果集重复
while (p<q&&nums[q]==nums[q-1]) {
q--;
}
p++;
q--;
//nums[i]+nums[p]+nums[q]<0说明nums[p]的值较小,不能满足和为0,P的值需要增加
}else if(nums[i]+nums[p]+nums[q]<0){
p++;
//nums[i]+nums[p]+nums[q]>0说明nums[q]的值较大,不能满足和为0,q的值需要减小
}else{
q--;
}
}
}
return countList;
}
public static void main(String[] args){
int[] nums = {-1,0,1,2,-1,-4};
List<List<Integer>> countList = threeSum(nums);
System.out.println(countList.size());
for(int i = 0;i < countList.size();i++){
System.out.println(countList.get(i));
}
}
}