Skip to content

Commit 869ca89

Browse files
committed
fix tc: O(n), sc: O(1)
1 parent 64e4ddc commit 869ca89

1 file changed

Lines changed: 18 additions & 25 deletions

File tree

Lines changed: 18 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,10 @@
11
/**
2-
ListNode는 파라미터로 current value와 next value를 지닌다.
3-
배열 메서드도 사용할 수 없다.
2+
list1, list2는 시작 노드 객체
3+
핵심은 '가위바위보 기찻길 룰'
4+
cur.next가 list1, list2 비교 결과를 배치해주는 역할
45
5-
나는 원초적인 방법으로 해결해보았다.
6-
result 배열에 모든 수를 다 넣고, sort()하는 것이다.
7-
여기서 중요한 점은 '어떻게 배열 → ListNode로 변경하느냐'이다.
8-
[1, 2, 3] 배열을 1 → 2 → 3 리스트 노드를 만들기 위해서는 컴퓨터 구조상 역방향인 3부터 가져와야한다.
9-
이때 사용한 메서드는 'reduceRight()'다.
10-
reduceRight() 메서드는 reduce() 작업순서의 역방향이다.
11-
12-
TC : O(nLogN) → sort()
13-
SC : O(n)
6+
TC : O(n)
7+
SC : O(1)
148
*/
159
/**
1610
* Definition for singly-linked list.
@@ -25,21 +19,20 @@ SC : O(n)
2519
* @return {ListNode}
2620
*/
2721
function mergeTwoLists(list1, list2) {
28-
let result = [];
29-
let node1 = list1;
30-
let node2 = list2;
31-
32-
while (node1 !== null) {
33-
result.push(node1.val);
34-
node1 = node1.next;
35-
}
22+
let dummy = new ListNode();
23+
let cur = dummy;
3624

37-
while (node2 !== null) {
38-
result.push(node2.val);
39-
node2 = node2.next;
25+
while (list1 && list2) {
26+
if (list1.val > list2.val) {
27+
cur.next = list2;
28+
list2 = list2.next;
29+
} else {
30+
cur.next = list1;
31+
list1 = list1.next;
32+
}
33+
cur = cur.next;
4034
}
35+
cur.next = list1 || list2; // 남아있는 원소 붙이기
4136

42-
return result
43-
.sort((a, b) => a - b)
44-
.reduceRight((next, val) => new ListNode(val, next), null);
37+
return dummy.next;
4538
}

0 commit comments

Comments
 (0)