|
| 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 70ms |
| 6 | + Space Complexity: O(N), Memory 51.63MB |
| 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 | + if(i>0 && nums[i]==nums[i-1]) continue; |
| 21 | + |
| 22 | + for(int j=i+1; j<nums.length; j++){ |
| 23 | + if(j>i+1 && nums[j]==nums[j-1]) continue; |
| 24 | + |
| 25 | + int target = -(nums[i]+nums[j]); |
| 26 | + if(nums[j]>target) continue; |
| 27 | + |
| 28 | + int count = number.getOrDefault(target,0); |
| 29 | + if(nums[i]==target) count--; |
| 30 | + if(nums[j]==target) count--; |
| 31 | + if(count<=0) continue; |
| 32 | + |
| 33 | + List<Integer> triplet = List.of(nums[i], nums[j], target); |
| 34 | + if(triplet.equals(lastTriplet)) continue; |
| 35 | + lastTriplet = triplet; |
| 36 | + triplets.add(triplet); |
| 37 | + } |
| 38 | + } |
| 39 | + return triplets; |
| 40 | + } |
| 41 | +} |
0 commit comments