1.HashSet
class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> millionYuanList = new ArrayList<>(); if(nums.length < 3) { return millionYuanList; } Arrays.sort(nums); for(int i = 0; i < nums.length; i++) { if(nums[i] > 0) break; Integer first = nums[i]; if(i > 0 && nums[i] == nums[i - 1]) continue; Set<Integer> set = new HashSet<>(); for(int j = i + 1; j < nums.length; j++) { int third = nums[j]; int second = -(first + third); if(set.contains(second)) { millionYuanList.add(new ArrayList<>(Arrays.asList(first, third, -(first + third)))); while(j < nums.length - 1 && nums[j] == nums[j + 1]) j++; } set.add(third); } } return millionYuanList; } }
2.HashMap
class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums);//排序 为了后面去重 HashMap<Integer,Integer> hm=new HashMap<>(); List<List<Integer>> list=new ArrayList<List<Integer>>(); for(int i=0;i<nums.length;i++){ hm.put(nums[i],i);//根据containsKey选择nums[i]为key } for(int i=0;i<nums.length;i++){ if(nums[i]>0)break; if(i>0 && nums[i]==nums[i-1])continue;//去重 int target=nums[i]*(-1); for(int j=i+1;j<nums.length;j++){ if(j>i+1 && nums[j]==nums[j-1])continue;//去重 int k=target-nums[j]; if(hm.containsKey(k)){ if(hm.get(k)>j ){ List<Integer> is=new ArrayList<Integer>(); is.add(nums[i]); is.add(nums[j]); is.add(k); list.add(is); } } } } return list; } }
3.什么都不用
class Solution{ public List<List<Integer>> threeSum(int[] nums){ int n = nums.length; Arrays.sort(nums); List<List<Integer>> ans = new ArrayList<List<Integer>>(); for(int i=0;i<n;i++){ if(i>0 && nums[i]==nums[i-1]) continue; int k = n-1; int target = -nums[i]; for(int j = i+1;j<n;j++){ if(j>i+1 && nums[j]==nums[j-1]) continue; while(j<k && nums[j]+nums[k]>target){ k--; } if(j==k) break; if(nums[j]+nums[k]==target){ List<Integer> list = new ArrayList<Integer>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[k]); ans.add(list); } } } return ans; } }
4.双指针
class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = new ArrayList<>(); Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) { return result; } if (i > 0 && nums[i] == nums[i - 1]) { continue; } int left = i + 1; int right = nums.length - 1; while (right > left) { int sum = nums[i] + nums[left] + nums[right]; if (sum > 0) { right--; } else if (sum < 0) { left++; } else { result.add(Arrays.asList(nums[i], nums[left], nums[right])); while (right > left && nums[right] == nums[right - 1]) right--; while (right > left && nums[left] == nums[left + 1]) left++; right--; left++; } } } return result; } }