|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +public class Geegong { |
| 4 | + |
| 5 | + /** |
| 6 | + * Time complexity : O(n^2) |
| 7 | + * space complexity : O(n^2) |
| 8 | + * @param nums |
| 9 | + * @return |
| 10 | + */ |
| 11 | + public List<List<Integer>> threeSum(int[] nums) { |
| 12 | + |
| 13 | + // μ€λ³΅λλ κ°μ μμ΄μΌ νκΈ°μ HashSet μΌλ‘ result |
| 14 | + HashSet<List<Integer>> result = new HashSet<>(); |
| 15 | + |
| 16 | + // Key : λ°°μ΄ μμ , value : List<String> μΈλ±μ€λ€ |
| 17 | + // elementMap μ two pointer μ κ°μ λν κ°μμ 0μ΄ λκΈ° μν μμλ₯Ό μ°ΎκΈ°μν΄ μ¬μ©λ κ²μ |
| 18 | + // tc : O(n) |
| 19 | + Map<Integer, List<Integer>> elementMap = new HashMap<>(); |
| 20 | + for (int index = 0; index<nums.length; index++) { |
| 21 | + int value = nums[index]; |
| 22 | + if (elementMap.containsKey(value)) { |
| 23 | + List<Integer> indices = elementMap.get(value); |
| 24 | + indices.add(index); |
| 25 | + elementMap.put(value, indices); |
| 26 | + } else { |
| 27 | + List<Integer> newIndices = new ArrayList<>(); |
| 28 | + newIndices.add(index); |
| 29 | + elementMap.put(value, newIndices); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // leftIndex : 0μμ λΆν° μμνλ index |
| 34 | + // rightIndex : nums.length - 1μμλΆν° κ°μνλ index |
| 35 | + // leftIndex > rightIndex λλ μκ°κΉμ§λ§ forλ¬Έμ λ κ²μ΄λ€. |
| 36 | + // tc : O(N^2 / 2) |
| 37 | + for (int leftIndex=0; leftIndex < nums.length; leftIndex++) { |
| 38 | + for (int rightIndex=nums.length - 1; rightIndex >= 0; rightIndex--) { |
| 39 | + |
| 40 | + if (leftIndex >= rightIndex) { |
| 41 | + break; |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + int leftValue = nums[leftIndex]; |
| 46 | + int rightValue = nums[rightIndex]; |
| 47 | + |
| 48 | + int neededValueToZero = -leftValue - rightValue; |
| 49 | + if (elementMap.containsKey(neededValueToZero)) { |
| 50 | + // elementMapμ value κ° leftIndex, rightIndex μ μλμ§ νμΈ |
| 51 | + |
| 52 | + List<Integer> indices = elementMap.get(neededValueToZero); |
| 53 | + // zero λ₯Ό λ§λ€ μ μλ μΈλ²μ¨° μΈλ±μ€κ° μλμ§ νμΈ |
| 54 | + int thirdIndex = findThirdIndexToBeZero(leftIndex, rightIndex, indices); |
| 55 | + if (-1 != thirdIndex) { |
| 56 | + List<Integer> newOne = new ArrayList<>(); |
| 57 | + newOne.add(nums[leftIndex]); |
| 58 | + newOne.add(nums[rightIndex]); |
| 59 | + newOne.add(nums[thirdIndex]); |
| 60 | + result.add(newOne.stream().sorted().toList()); |
| 61 | + } |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return result.stream().toList(); |
| 69 | + |
| 70 | + } |
| 71 | + |
| 72 | + public int findThirdIndexToBeZero(int leftIndex, int rightIndex, List<Integer> indices) { |
| 73 | + for (int index : indices) { |
| 74 | + if (index != leftIndex && index != rightIndex) { |
| 75 | + return index; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + return -1; |
| 80 | + } |
| 81 | +} |
| 82 | + |
0 commit comments