【LeetCode】 15. 3Sum 三数之和(Medium)(JAVA)

【LeetCode】 15. 3Sum 三数之和(Medium)(JAVA)

题目地址: https://leetcode.com/problems/longest-common-prefix/

题目描述:

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

题目大意

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

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

解题方法

为了防止重复,先对数组进行排序,然后用一个Map 把所有的元素存起来,两重循环, O(n^2) 耗时

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            Integer temp = map.get(nums[i]);
            if (temp == null) {
                map.put(nums[i], 1);
            } else {
                map.put(nums[i], temp + 1);
            }
        }
        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i -1]) continue; 
            for (int j = i + 1; j < nums.length - 1; j++) {
                if (j > i + 1 && nums[j] == nums[j -1]) continue;
                int three = - nums[i] - nums[j];
                Integer count = map.get(three);
                if (count == null || three < nums[j]) continue;
                if ((three == nums[i] || three == nums[j]) && count <= 1) {
                    continue;
                }
                if (three == nums[i] && three == nums[j] && count <= 2) {
                    continue;
                }
                List<Integer> cur = new ArrayList<>();
                cur.add(nums[i]);
                cur.add(nums[j]);
                cur.add(three);
                res.add(cur);
            }
        }
        return res;
    }
}

执行用时 : 101 ms, 在所有 Java 提交中击败了 15.79% 的用户
内存消耗 : 45.4 MB, 在所有 Java 提交中击败了 96.25% 的用户

发布了29 篇原创文章 · 获赞 3 · 访问量 1108

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104552456
今日推荐