[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;
    }

}

  

 

posted @ 2017-12-30 19:04  zxzhang  阅读(219)  评论(0编辑  收藏  举报