1. 程式人生 > >[LeetCode] 15. 3Sum

[LeetCode] 15. 3Sum

bsp 輸出 傳送門 script java dup str lang ==

傳送門

Description

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]
]

思路

題意:給出一串整數值,輸出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