#15 3Sum

问题:

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

代码:

package solution;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution15 {
    public static List> threeSum(int[] nums) {
        List> res = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length-2; i++){
            if (i > 0 && nums[i] == nums[i - 1]) {              // skip same result
                continue;
            }
            int j = i+1, k = nums.length-1;
            int target = -nums[i];
            while(j target){
                    k--;
                }
                else{
                    j++;
                }
            }
        }
        return res;
    }
    public static void main(String[] args){
        int[] a = new int[] {-1,0,1,2,-1,-4};
        System.out.println(threeSum(a));
    }
}

你可能感兴趣的:(#15 3Sum)