three sum

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

The idea is to sort an input array and then run through all indices of a possible first element of a triplet. For each possible first element we make a standard bi-directional 2Sum sweep of the remaining part of the array. Also we want to skip equal elements to avoid duplicates in the answer without making a set or smth like that.

思考点: 是否有重复

public List> threeSum(int[] nums) { Arrays.sort(nums); List> r = new LinkedList<>(); for (int i=0; i0 && nums[i]!=nums[i-1])) { int j = i+1, k = nums.length-1, sum = -nums[i]; while (j < k) { if (j!=i+1 && nums[j]==nums[j-1]) j++; else if (k!=nums.length-1 && nums[k]==nums[k+1]) k--; else if (nums[j] + nums[k] == sum) { r.add(Arrays.asList(nums[i], nums[j], nums[k])); j++; k--; } else if (nums[j] + nums[k] < sum) j++; else k--; } } return r; }

results matching ""

    No results matching ""