15 三数之和(LeetCode HOT 100)

描述:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

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

示例 1:

输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]

示例 2:

输入:nums = []
输出:[]

示例 3:

输入:nums = [0]
输出:[]

提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105

Soulution:

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        // 使用哈希表,O(1)查找想要的数字
        HashMap<Integer, Integer> numMap = new HashMap<>(nums.length);

        // 因为不允许出现重复答案,一个元素最多出现三次,大于三次的数字是无用的,可剔除
        List<Integer> filterList = new ArrayList<>();
        for (int num : nums) {
            Integer count = numMap.getOrDefault(num, 0);
            if (count < 3) {
                filterList.add(num);
                numMap.put(num, (count + 1));
            }
        }

        for (int i = 0; i < filterList.size(); ++i) {
            numMap.put(filterList.get(i), i);
        }
        for (int i = 0; i < filterList.size(); ++i) {
            for (int j = i + 1; j < filterList.size(); ++j) {
                int a = filterList.get(i);
                int b = filterList.get(j);
                int c = -a - b;
                Integer index = numMap.get(c);
                if (index != null && index != i && index != j) {
                    List<Integer> result = new ArrayList<>(Arrays.asList(a, b, c));
                    Collections.sort(result);
                    results.add(result);
                }
            }
        }
        // 去重
        return results.stream().distinct().collect(Collectors.toList());
    }

Idea:
使用哈希表,O(1)查找想要的数字
因为不允许出现重复答案,一个元素最多出现三次,大于三次的数字是无用的,可剔除,减少数据规模

Reslut:

Impore:
可以使用排序+双指针优化。

posted @ 2022-04-08 21:40  supermingjun  阅读(28)  评论(0编辑  收藏  举报