|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +class Solution { |
| 4 | + public List<List<Integer>> threeSum(int[] nums) { |
| 5 | + Arrays.sort(nums); |
| 6 | + Set<List<Integer>> set = new HashSet<>(); |
| 7 | + for(int i = 0; i < nums.length && nums[i] <= 0; i++) { |
| 8 | + int j = i+1; |
| 9 | + int k = nums.length - 1; |
| 10 | + while(j < k) { |
| 11 | + int sum = nums[i] + nums[j] + nums[k]; |
| 12 | + if (sum > 0) { |
| 13 | + k--; |
| 14 | + continue; |
| 15 | + } |
| 16 | + |
| 17 | + if (sum < 0) { |
| 18 | + j++; |
| 19 | + continue; |
| 20 | + } |
| 21 | + |
| 22 | + set.add(List.of(nums[i], nums[j], nums[k])); |
| 23 | + j++; |
| 24 | + k--; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + return new ArrayList<>(set); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +/* |
| 33 | +import java.util.*; |
| 34 | +import java.util.stream.Collectors; |
| 35 | +
|
| 36 | +class Solution { |
| 37 | + public List<List<Integer>> threeSum(int[] nums) { |
| 38 | + Map<Integer, Integer> map = new HashMap<>(); |
| 39 | + for(int i = 0; i < nums.length; i++) { |
| 40 | + map.put(nums[i], i); |
| 41 | + } |
| 42 | +
|
| 43 | + Set<Triplet> set = new HashSet<>(); |
| 44 | + for(int i = 0; i < nums.length; i++) { |
| 45 | + int target = -nums[i]; |
| 46 | + for(int j = i+1; j < nums.length; j++) { |
| 47 | + int operand = target - nums[j]; |
| 48 | + if (map.containsKey(operand) && map.get(operand) > j) { |
| 49 | + set.add(new Triplet(nums[i], nums[j], operand)); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | +
|
| 54 | + return set.stream().map(t -> List.of(t.triplet[0], t.triplet[1], t.triplet[2])).collect(Collectors.toList()); |
| 55 | + } |
| 56 | +} |
| 57 | +
|
| 58 | +class Triplet { |
| 59 | + int[] triplet; |
| 60 | +
|
| 61 | + Triplet(int first, int second, int third) { |
| 62 | + this.triplet = new int[] { first, second, third }; |
| 63 | + Arrays.sort(triplet); |
| 64 | + } |
| 65 | +
|
| 66 | + @Override |
| 67 | + public boolean equals(Object o) { |
| 68 | + if (this == o) return true; |
| 69 | + if (!(o instanceof Triplet that)) { |
| 70 | + return false; |
| 71 | + } |
| 72 | +
|
| 73 | + for(int i = 0; i<3; i++) { |
| 74 | + if (this.triplet[i] != that.triplet[i]) { |
| 75 | + return false; |
| 76 | + } |
| 77 | + } |
| 78 | +
|
| 79 | + return true; |
| 80 | + } |
| 81 | +
|
| 82 | + @Override |
| 83 | + public int hashCode() { |
| 84 | + return Objects.hash(triplet[0], triplet[1], triplet[2]); |
| 85 | + } |
| 86 | +} |
| 87 | +*/ |
0 commit comments