Skip to content

Commit 038e655

Browse files
authored
Merge pull request #1834 from suhyenim/5th/week04
[suhyenim] WEEK04 solutions
2 parents e33df7b + 49ba241 commit 038e655

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

merge-two-sorted-lists/suhyenim.java

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/* [5th/week04] 21. Merge Two Sorted Lists
2+
3+
1. 문제 요약
4+
링크: https://leetcode.com/problems/merge-two-sorted-lists/description/
5+
두 개의 정렬된 리스트를 오름차순으로 병합한 리스트를 반환
6+
7+
2. 문제 풀이
8+
풀이1: 두 리스트의 head 비교해서 더 작은 값 선택 -> 한쪽이 null되면 재귀를 통해 이어붙여서 마무리
9+
성공/실패: 시간 복잡도는 O(m+n), 공간 복잡도는 O(m+n)
10+
=> Time: 0 ms (100%), Space: 43 MB (8.18%)
11+
12+
class Solution {
13+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
14+
if (l1 == null || l2 == null)
15+
return l1 != null ? l1 : l2;
16+
if (l1.val < l2.val) {
17+
l1.next = mergeTwoLists(l1.next, l2);
18+
return l1;
19+
} else {
20+
l2.next = mergeTwoLists(l1, l2.next);
21+
return l2;
22+
}
23+
}
24+
}
25+
26+
풀이2: 두 리스트의 head 비교해서 더 작은 값 선택해서 node.next에 연결 -> 한쪽이 null되면 dummy.next 반환
27+
성공/실패: 시간 복잡도는 O(m+n), 공간 복잡도는 O(1)
28+
=> Time: 0 ms (100%), Space: 43.2 MB (8.18%)
29+
30+
class Solution {
31+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
32+
ListNode dummy = new ListNode(-1);
33+
ListNode node = dummy;
34+
35+
while (l1 != null && l2 != null) {
36+
if (l1.val < l2.val) {
37+
node.next = l1;
38+
l1 = l1.next;
39+
} else {
40+
node.next = l2;
41+
l2 = l2.next;
42+
}
43+
node = node.next;
44+
}
45+
46+
node.next = l1 != null ? l1 : l2;
47+
return dummy.next;
48+
}
49+
}
50+
51+
*/
52+
53+
/**
54+
* Definition for singly-linked list.
55+
* public class ListNode {
56+
* int val;
57+
* ListNode next;
58+
* ListNode() {}
59+
* ListNode(int val) { this.val = val; }
60+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
61+
* }
62+
*/
63+
64+
class Solution {
65+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
66+
ListNode dummy = new ListNode(-1);
67+
ListNode node = dummy;
68+
69+
while (l1 != null && l2 != null) {
70+
if (l1.val < l2.val) {
71+
node.next = l1;
72+
l1 = l1.next;
73+
} else {
74+
node.next = l2;
75+
l2 = l2.next;
76+
}
77+
node = node.next;
78+
}
79+
80+
node.next = l1 != null ? l1 : l2;
81+
return dummy.next;
82+
}
83+
}

0 commit comments

Comments
 (0)