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.
publicclassSolution{ public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = new ArrayList<>(); Arrays.sort(nums); int target = 0, m = nums.length; for ( int i = 0, bound = m - 2 ; i < bound && nums[i] <= target ; ) { int l = i + 1, r = m - 1, sum = target - nums[i]; while ( l < r ) { int temp_sum = nums[l] + nums[r]; if ( temp_sum < sum ) l++; elseif ( temp_sum > sum ) r--; else { List<Integer> item = new ArrayList<>(); item.add(nums[i]); item.add(nums[l]); item.add(nums[r]); result.add(item); l++; while ( l < r && nums[l] == nums[l-1] ) l++; r--; while ( l < r && nums[r] == nums[r+1] ) r--; } } i++; while ( i < bound && nums[i] == nums[i-1] ) i++; } return result; } }