|
| 1 | +/* |
| 2 | + Problem: https://leetcode.com/problems/3sum/ |
| 3 | + Description: return all the triplets (i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0) |
| 4 | + Concept: Array, Two Pointers, Sorting |
| 5 | + Time Complexity: O(N²), Runtime 1107ms |
| 6 | + Space Complexity: O(N), Memory 54.20MB |
| 7 | +*/ |
| 8 | +class Solution { |
| 9 | + public List<List<Integer>> threeSum(int[] nums) { |
| 10 | + Map<Integer, Integer> number = new HashMap<>(); |
| 11 | + for(int i=0; i<nums.length; i++) { |
| 12 | + number.put(nums[i], number.getOrDefault(nums[i], 0)+1); |
| 13 | + } |
| 14 | + |
| 15 | + Arrays.sort(nums); |
| 16 | + Set<List<Integer>> set = new HashSet<>(); |
| 17 | + List<List<Integer>> triplets = new ArrayList<>(); |
| 18 | + List<Integer> lastTriplet = null; |
| 19 | + for(int i=0; i<nums.length-1; i++) { |
| 20 | + for(int j=i+1; j<nums.length; j++){ |
| 21 | + int twoSum = nums[i]+nums[j]; |
| 22 | + if(nums[j]>-twoSum) continue; |
| 23 | + |
| 24 | + int count = number.getOrDefault(-twoSum,0); |
| 25 | + if(nums[i]==-twoSum) count--; |
| 26 | + if(nums[j]==-twoSum) count--; |
| 27 | + if(count<=0) continue; |
| 28 | + |
| 29 | + List<Integer> triplet = List.of(nums[i], nums[j], -twoSum); |
| 30 | + int setSize = set.size(); |
| 31 | + set.add(triplet); |
| 32 | + if(setSize != set.size()) triplets.add(triplet); |
| 33 | + } |
| 34 | + } |
| 35 | + return triplets; |
| 36 | + } |
| 37 | +} |
0 commit comments