File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ layout : post
3
+ title : (Leetcode) 21 - Merge Two Sorted Lists
4
+ categories : [스터디-알고리즘]
5
+ tags :
6
+ [
7
+ 자바,
8
+ java,
9
+ linked list,
10
+ 연결 리스트,
11
+ 리트코드,
12
+ Leetcode,
13
+ 알고리즘,
14
+ algorithm,
15
+ neetcode,
16
+ ]
17
+ date : 2024-04-29 13:50:00 +0900
18
+ toc : true
19
+ ---
20
+
21
+ 기회가 되어 [ 달레님의 스터디] ( https://github.com/DaleStudy/leetcode-study ) 에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
22
+
23
+ [ https://neetcode.io/practice ] ( https://neetcode.io/practice )
24
+
25
+ ---
26
+
27
+ 2주간 미션이 나와서 다시 풀기 시작하였다.
28
+
29
+ [ https://leetcode.com/problems/merge-two-sorted-lists/description/ ] ( https://leetcode.com/problems/merge-two-sorted-lists/description/ )
30
+
31
+ ## 내가 작성한 풀이
32
+
33
+ 두 리스트에서 작은 값을 찾고 작은 값을 새 ListNode에 추가한 뒤 기존의 리스트에서는 지워준다.
34
+
35
+ ``` java
36
+ class Solution {
37
+ public ListNode mergeTwoLists (ListNode list1 , ListNode list2 ) {
38
+ ListNode head = null ;
39
+ ListNode tail = null ;
40
+
41
+ while (! (list1 == null && list2 == null )) {
42
+ ListNode selected;
43
+ if (list1 == null ) {
44
+ selected = list2;
45
+ list2 = list2. next;
46
+ } else if (list2 == null ) {
47
+ selected = list1;
48
+ list1 = list1. next;
49
+ } else if (list1. val < list2. val) {
50
+ selected = list1;
51
+ list1 = list1. next;
52
+ } else {
53
+ selected = list2;
54
+ list2 = list2. next;
55
+ }
56
+
57
+ ListNode newNode = new ListNode (selected. val);
58
+ if (head == null ) {
59
+ head = newNode;
60
+ } else {
61
+ tail. next = newNode;
62
+ }
63
+
64
+ tail = newNode;
65
+ }
66
+
67
+ return head;
68
+ }
69
+ }
70
+ ```
71
+
72
+ ### TC, SC
73
+
74
+ 시간 복잡도는 O(n)이고, 공간 복잡도는 O(n)이다.
You can’t perform that action at this time.
0 commit comments