[leetcode note] 3Sum

时间: 2019-12-15 2:46 PM
题目地址: https://leetcode.com/problems/3sum/

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:
结果集中不得包含重复的组合。

给定一个由n个整数组成的数组,是否存在以a + b + c = 0的元素a,b,c? 在给出零和的数组中查找所有唯一的三元组。

Example:

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

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

Solution:

public List<List<Integer>> threeSum(int[] nums) {
    if (null == nums || nums.length < 3) {
        return Collections.emptyList();
    }
    Arrays.sort(nums);
    List<List<Integer>> list = new ArrayList<>();
    for (int i = 0; i < nums.length; ++i) {
        if (i > 0 && nums[i] == nums[i - 1]) {
            continue;
        }
        int left = i + 1, right = nums.length - 1;
        while (left < right) {
            int sum = nums[i] + nums[left] + nums[right];
            if (sum == 0) {
                List<Integer> item = new ArrayList<>(3);
                item.add(nums[i]);
                item.add(nums[left]);
                item.add(nums[right]);
                list.add(item);
                ++left;
                --right;
                while (left < right) {
                    if (nums[left] == nums[left - 1]) {
                        ++left;
                    } else if (nums[right] == nums[right + 1]) {
                        --right;
                    } else {
                        break;
                    }
                }
            } else if (sum > 0) {
                --right;
            } else {
                ++left;
            }
        }
    }
    return list;
}

Runtime: 30 ms, faster than 83.38% of Java online submissions for 3Sum.
Memory Usage: 42.8 MB, less than 100.00% of Java online submissions for 3Sum.

欢迎关注公众号(代码如诗):
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值