Skip to content

Commit

Permalink
update post
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-jonghoonpark committed May 29, 2024
1 parent e6cbc3f commit 12566a7
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions _posts/2024-05-07-leetcode-15.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,3 +281,55 @@ while (j > i && nums[i] == nums[i - 1])
모범답안도 동일하게 시간 복잡도는 O(n^2), 공간 복잡도는 O(n^2) 이다. 하지만 실제 동작은 20-30ms 로 끝나기 떄문에 약 33배 차이가 난다.

![best answer](/assets/images/2024-05-07-leetcode-15/best-answer.png)

### 다시 풀어보기 (240529)

지난번에 풀었던 기억을 되살려서 이번에는 도움 없이 다시 풀어봤다. 코드를 좀 더 이해하기 쉽게 배치했다고 생각한다.

```java
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);

List<List<Integer>> result = new ArrayList<>();

int lastOne = Integer.MIN_VALUE;
for (int i = 0; i < nums.length - 1; i++) {
int num = nums[i];
if (lastOne == num) {
continue;
}

twoSum(result, nums, i);
lastOne = num;
}

return result;
}

public void twoSum(List<List<Integer>> result, int[] nums, int targetIndex) {
int target = -nums[targetIndex];

int i = targetIndex + 1;
int j = nums.length - 1;
while (i < j) {
int twoSum = nums[i] + nums[j];

if (target > twoSum) {
i++;
}

if (target < twoSum) {
j--;
}

if (target == twoSum) {
result.add(List.of(-target, nums[i], nums[j]));
int current = nums[i];
while (i < nums.length - 2 && current == nums[i + 1]) {
i++;
}
i++;
}
}
}
```

0 comments on commit 12566a7

Please sign in to comment.