[LeetCode] 15. 3Sum

Posted zzy19961112

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 15. 3Sum相关的知识,希望对你有一定的参考价值。

传送门

Description

Given an array S of n integers, are there elements abc 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]
]

思路

题意:给出一串整数值,输出a + b + c = 0的方案

题解:求三个数之和为0的方案则可以转换成求两个数为0的方案。

 

public class Solution {
    //72ms
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>>res = new ArrayList<>();
        int len = nums.length;
        Arrays.sort(nums);
        for (int i = 0;i < len - 2;i++){
            int sum = -nums[i];
            int left = i + 1,right = len - 1;
            while (left < right){
                if (nums[left] + nums[right] < sum){
                    left++;
                } else if (nums[left] + nums[right] > sum){
                    right--;
                } else{
                    res.add(Arrays.asList(nums[i],nums[left],nums[right]));
                    while (++left < right && nums[left] == nums[left - 1]){}
                    while (--right > left && nums[right] == nums[right + 1]){}
                }
            }
            while (i + 1 < len - 2 && nums[i + 1] == nums[i]){
                i++;
            }
        }
        return res;
    }

}

  

 

以上是关于[LeetCode] 15. 3Sum的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 15 3Sum

[leetcode][15] 3Sum

Leetcode 15. 3Sum(python)

Leetcode 15. 3Sum

leetcode15 3Sum

[leetcode]15. 3Sum[UNSOLVED]