zhuangjinxin / leetcode

算法、数据库、面向对象设计、系统设计
https://leetcode.com
0 stars 0 forks source link

3Sum #15

Open zhuangjinxin opened 6 years ago

zhuangjinxin commented 6 years ago

题目: 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]
]
zhuangjinxin commented 6 years ago

解答

public List<List<Integer>> threeSum(int[] nums) {
    Arrays.sort(nums);
    System.out.println(Arrays.toString(nums));
    List<List<Integer>> list = new ArrayList<List<Integer>>();

    if (nums.length<3){
        return list;
    }
    for(int i=0;i<=nums.length-3;i++){
        for(int j=i+1;j<=nums.length-2;j++){
            for(int k=j+1;k<=nums.length-1;k++){
                if(nums[i]+nums[j]+nums[k]==0){
                    List<Integer> temp = new ArrayList<Integer>();
                    temp.add(nums[i]);
                    temp.add(nums[j]);
                    temp.add(nums[k]);
                    list.add(temp);
                }
            }
        }
    }
    return list;
}

问题:

  1. 没有想到if(nums.length<3)的判断;