15 三数之和(LeetCode HOT 100)

发布时间:2022-06-20 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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 &amp;& 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:

15 三数之和(LeetCode HOT 100)

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

脚本宝典总结

以上是脚本宝典为你收集整理的15 三数之和(LeetCode HOT 100)全部内容,希望文章能够帮你解决15 三数之和(LeetCode HOT 100)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。