3Sum

本贴最后更新于 2249 天前,其中的信息可能已经时移世异

题目描述

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

For example, given array S = [-1, 0, 1, 2, -1, -4],

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

解题思路

转换为 2Sum 问题。target 为-nums[i]。

代码

class Solution {
    List<List<Integer>> ret = new ArrayList<>();
    
    public List<List<Integer>> threeSum(int[] nums) {
        if (nums == null || nums.length < 3)
            return ret;
        
        Arrays.sort(nums);
        
        for (int i = 0; i < nums.length-2; i++) {
            if (i > 0 && nums[i] == nums[i-1])
                continue;
            twoSum(nums, i+1);
        }
        return ret;
    }
    
    private void twoSum(int[] nums, int start) {
        int left = start;
        int right = nums.length-1;
        while (left < right) {
            if (nums[left] + nums[right] + nums[start-1] == 0) {
                ArrayList<Integer> list = new ArrayList<>();
                list.add(nums[start-1]);
                list.add(nums[left]);
                list.add(nums[right]);
                ret.add(list);
                while (left < right && nums[left] == nums[left+1])
                    left++;
                while (left < right && nums[right] == nums[right-1])
                    right--;
                left++;
                right--;
            } else if (nums[left] + nums[right] + nums[start-1] < 0) {
                left++;
            } else if (nums[left] + nums[right] + nums[start-1] > 0)
                right--;
        }
    }
}
  • 算法
    388 引用 • 254 回帖 • 22 关注
  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    209 引用 • 72 回帖

相关帖子

回帖

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...