15. 三数之和

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != ji != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请

你返回所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组

class Solution {
    public List> threeSum(int[] nums) {
        List> millionYuanList = new ArrayList<>();
        //人都不够仨,还三胎。。。
        if(nums.length < 3) {
            return millionYuanList;
        }

        Arrays.sort(nums);      //孩子们按个头排好队
        for(int i = 0; i < nums.length; i++) {
            //如果老大都大于0,后面的兄弟肯定都大于0,直接返回就行
            if(nums[i] > 0) break;
            Integer first = nums[i];    //老大出列,站好别动

            //老大想再往后占个位,多领一次奖,这可是不行滴。。。还是回家让妈妈再给生三个小弟弟吧^_^
            if(i > 0 && nums[i] == nums[i - 1]) continue;

            //画个圈,让各家老二在里面呆着
            Set set = new HashSet<>();
            for(int j = i + 1; j < nums.length; j++) {
                //老三出列,一会你和老大一块到圈里找老二
                int third = nums[j];
                int second = -(first + third);      //目标是:老大 + 老二 + 老三 = 0
                //找到老二了,记到中奖名单上
                if(set.contains(second)) {
                    millionYuanList.add(new ArrayList<>(Arrays.asList(first, third, -(first + third))));

                    //老三也想多领奖。。。额。。。等会一块回家找妈妈去吧
                    while(j < nums.length - 1 && nums[j] == nums[j + 1]) j++;
                }
                set.add(third);
            }
        }
        return millionYuanList;
    }
}

三层循环

public class Solution {

    public static void main(String[] args) {
        int[] nums = new int[]{-4, -2, 1, -5, -4, -4, 4, -2, 0, 4, 0, -2, 3, 1, -5, 0};
        System.out.println(threeSum(nums));
    }

    public static List> threeSum(int[] nums) {
        List> threes = new ArrayList<>();
        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 (i == j || j == k || i == k) {
                        continue;
                    }
                    if (nums[i] + nums[j] + nums[k] == 0) {
                        List three = new ArrayList<>();
                        three.add(nums[i]);
                        three.add(nums[j]);
                        three.add(nums[k]);
                        if (!contain(three, threes)) {
                            threes.add(three);
                        }
                    }
                }
            }
        }
        return threes;
    }

    public static boolean contain(List three, List> threes) {
        for (List list : threes) {
            if (three.contains(list.get(0)) && three.contains(list.get(1)) && three.contains(list.get(2))
                    && list.contains(three.get(0)) && list.contains(three.get(1)) && list.contains(three.get(2))) {
                return true;
            }
        }
        return false;
    }
}

你可能感兴趣的:(leetcode,算法,排序算法)