1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | public class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> result = new ArrayList<List<Integer>>(); for (int i = 0; i < nums.length-2; i++){ if (i == 0 || nums[i] != nums[i-1]){ List<List<Integer>> temp = twoSum(nums, i+1, 0-nums[i]); for (List<Integer> list:temp){ list.add(0, nums[i]); result.add(list); } } } return result; } public List<List<Integer>> twoSum(int nums[], int start, int target){ List<List<Integer>> result = new ArrayList<List<Integer>>(); int left = start; int end = nums.length-1; while (left < end){ int sum = nums[left]+nums[end]; if (sum == target){ List<Integer> temp = new ArrayList<Integer>(); temp.add(nums[left]); temp.add(nums[end]); result.add(temp); while (left < end-1 && nums[left] == nums[left+1]) left++; while (left+1 < end && nums[end] == nums[end-1]) end--; left++; end--; }else if (sum > target){ end--; }else{ left++; } } return result; } } |
Wednesday, November 25, 2015
[leetcode] 3 Sum
记得去除重复值
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment