File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change @@ -281,3 +281,55 @@ while (j > i && nums[i] == nums[i - 1])
281
281
모범답안도 동일하게 시간 복잡도는 O(n^2), 공간 복잡도는 O(n^2) 이다. 하지만 실제 동작은 20-30ms 로 끝나기 떄문에 약 33배 차이가 난다.
282
282
283
283
![ best answer] ( /assets/images/2024-05-07-leetcode-15/best-answer.png )
284
+
285
+ ### 다시 풀어보기 (240529)
286
+
287
+ 지난번에 풀었던 기억을 되살려서 이번에는 도움 없이 다시 풀어봤다. 코드를 좀 더 이해하기 쉽게 배치했다고 생각한다.
288
+
289
+ ``` java
290
+ public List<List<Integer > > threeSum(int [] nums) {
291
+ Arrays . sort(nums);
292
+
293
+ List<List<Integer > > result = new ArrayList<> ();
294
+
295
+ int lastOne = Integer . MIN_VALUE ;
296
+ for (int i = 0 ; i < nums. length - 1 ; i++ ) {
297
+ int num = nums[i];
298
+ if (lastOne == num) {
299
+ continue ;
300
+ }
301
+
302
+ twoSum(result, nums, i);
303
+ lastOne = num;
304
+ }
305
+
306
+ return result;
307
+ }
308
+
309
+ public void twoSum(List<List<Integer > > result, int [] nums, int targetIndex) {
310
+ int target = - nums[targetIndex];
311
+
312
+ int i = targetIndex + 1 ;
313
+ int j = nums. length - 1 ;
314
+ while (i < j) {
315
+ int twoSum = nums[i] + nums[j];
316
+
317
+ if (target > twoSum) {
318
+ i++ ;
319
+ }
320
+
321
+ if (target < twoSum) {
322
+ j-- ;
323
+ }
324
+
325
+ if (target == twoSum) {
326
+ result. add(List . of(- target, nums[i], nums[j]));
327
+ int current = nums[i];
328
+ while (i < nums. length - 2 && current == nums[i + 1 ]) {
329
+ i++ ;
330
+ }
331
+ i++ ;
332
+ }
333
+ }
334
+ }
335
+ ```
You can’t perform that action at this time.
0 commit comments