|
| 1 | +package amazon; |
| 2 | + |
| 3 | + |
| 4 | +// 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. |
| 5 | + |
| 6 | +// Note: The solution set must not contain duplicate triplets. |
| 7 | + |
| 8 | +// For example, given array S = [-1, 0, 1, 2, -1, -4], |
| 9 | + |
| 10 | +// A solution set is: |
| 11 | +// [ |
| 12 | +// [-1, 0, 1], |
| 13 | +// [-1, -1, 2] |
| 14 | +// ] |
| 15 | + |
| 16 | +import java.util.ArrayList; |
| 17 | +import java.util.Arrays; |
| 18 | +import java.util.List; |
| 19 | + |
| 20 | +/** |
| 21 | + * Created by anduo on 17-3-13. |
| 22 | + */ |
| 23 | +public class ThreeSum { |
| 24 | + |
| 25 | + // 把3sum的问题,降级到2sum问题 |
| 26 | + public List<List<Integer>> threeSum(int[] nums) { |
| 27 | + List<List<Integer>> result = new ArrayList<>(); |
| 28 | + Arrays.sort(nums); |
| 29 | + |
| 30 | + for (int i = 0; i < nums.length; i++) { |
| 31 | + if (i > 0 && nums[i] == nums[i - 1]) {// 这道题用不到这个条件,因为题目说了不考虑重复元素 |
| 32 | + continue; |
| 33 | + } |
| 34 | + int left = i + 1; |
| 35 | + int right = nums.length - 1; |
| 36 | + int target = -nums[i]; |
| 37 | + twoSum(nums, left, right, target, result); |
| 38 | + } |
| 39 | + return result; |
| 40 | + } |
| 41 | + |
| 42 | + public void twoSum(int[] nums, |
| 43 | + int left, |
| 44 | + int right, |
| 45 | + int target, |
| 46 | + List<List<Integer>> results) { |
| 47 | + // 充分利用有序这样一个特点 |
| 48 | + while (left < right) { |
| 49 | + if (nums[left] + nums[right] == target) { |
| 50 | + ArrayList<Integer> triple = new ArrayList<>(); |
| 51 | + triple.add(-target); |
| 52 | + triple.add(nums[left]); |
| 53 | + triple.add(nums[right]); |
| 54 | + results.add(triple); |
| 55 | + |
| 56 | + left++; |
| 57 | + right--; |
| 58 | + // skip duplicate pairs with the same left |
| 59 | + while (left < right && nums[left] == nums[left - 1]) { |
| 60 | + left++; |
| 61 | + } |
| 62 | + // skip duplicate pairs with the same right |
| 63 | + while (left < right && nums[right] == nums[right + 1]) { |
| 64 | + right--; |
| 65 | + } |
| 66 | + } else if (nums[left] + nums[right] < target) { |
| 67 | + left++; |
| 68 | + } else { |
| 69 | + right--; |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | +} |
0 commit comments