|
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 |
| -*/ |
| 1 | +/** |
| 2 | + * <a href="https://leetcode.com/problems/3sum/">week02-4.3sum</a> |
| 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 2021ms |
| 6 | + * Space Complexity: O(N), Memory 53.9MB |
| 7 | + */ |
| 8 | + |
8 | 9 | class Solution {
|
9 | 10 | 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); |
| 11 | + Map<Integer, Integer> map = new HashMap<>(); |
| 12 | + for(int i=0; i<nums.length; i++){ |
| 13 | + map.put(nums[i], i); |
13 | 14 | }
|
14 | 15 |
|
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); |
| 16 | + Set<List<Integer>> triplets = new HashSet<>(); |
| 17 | + for(int i=0; i<nums.length-2; i++){ |
| 18 | + for(int j=i+1; j<nums.length-1; j++){ |
| 19 | + int sum = nums[i]+nums[j]; |
| 20 | + if(map.containsKey(-sum) && map.get(-sum) > j){ |
| 21 | + List<Integer> list = Arrays.asList(nums[i],nums[j],-sum); |
| 22 | + Collections.sort(list); |
| 23 | + triplets.add(list); |
| 24 | + } |
37 | 25 | }
|
38 | 26 | }
|
39 |
| - return triplets; |
| 27 | + |
| 28 | + return new ArrayList<>(triplets); |
40 | 29 | }
|
41 | 30 | }
|
0 commit comments