题目
https://leetcode-cn.com/problems/3sum
解法
固定一个数,两数之和
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 42 43
| class Solution { public List<List<Integer>> threeSum(int[] nums) { if (nums == null || nums.length == 0) { return new ArrayList<List<Integer>>(); }
Arrays.sort(nums); int len = nums.length; List<List<Integer>> res = new ArrayList<List<Integer>>(); for(int first=0; first<len; first++) { if(first>0 && nums[first] == nums[first-1]) { continue; } int target = -nums[first]; int third = len-1; for(int second=first+1; second<third; ) { if(second>first+1 && nums[second] == nums[second-1]) { second++; continue; } if(second == third) { break; } if(nums[second]+nums[third] == target) { List<Integer> list = new ArrayList<>(); list.add(nums[first]); list.add(nums[second]); list.add(nums[third]); res.add(list); second++; third--; } else if(nums[second]+nums[third] < target) { second++; } else { third--; } } } return res; } }
|