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:
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
package com.mingxin.leetcode.leet_15; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by Administrator on 2016/1/25. */ public class ThreeSum { public static void main(String[] args){ int num[] = {-1, -20, -5, -7, 0, 1, 2, 7, 6, 10}; List<List<Integer>> result = threeSum(num); for(List<Integer> item1:result){ System.out.println("{" + item1.get(0) + ", " + item1.get(1) + ", " + item1.get(2) + "}"); } } public static List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(nums.length<3||nums == null){ return new ArrayList<List<Integer>>(); } Arrays.sort(nums); for(int i = 0; i <= nums.length-3; i++){ if(i==0||nums[i]!=nums[i-1]){ int low = i+1; int high = nums.length-1; while(low<high){ int sum = nums[i]+nums[low]+nums[high]; if(sum == 0){ ArrayList<Integer> unit = new ArrayList<Integer>(); unit.add(nums[i]); unit.add(nums[low]); unit.add(nums[high]); res.add(unit); low++; high--; while(low<high&&nums[low]==nums[low-1]){ low++; } while(low<high&&nums[high]==nums[high+1]){ high--; } }else if(sum > 0){ high --; } else{ low ++; } } } } return res; } }