File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Definition for singly-linked list.
2
+ # class ListNode:
3
+ # def __init__(self, val=0, next=None):
4
+ # self.val = val
5
+ # self.next = next
6
+ class Solution :
7
+ def mergeTwoLists (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
8
+ """
9
+ Intuition:
10
+ ๋ ๋ฆฌ์คํธ์ ์์๋ฅผ ๊ฐ๊ฐ ๋น๊ตํ๋ฉด์ ํ๋ฒ์ฉ ์ค์บํ๋ค.
11
+ ๊ฒฐ๊ณผ์ ์ผ๋ก ํ๋ฒ์ฉ๋ง ์ค์บํ๋ฉด ์ ๋ ฌํ ์ ์๋ค.
12
+
13
+ Time Complexity:
14
+ O(N):
15
+ ๋๊ฐ์ ๋ฆฌ์คํธ๋ฅผ 1๋ฒ ์ํํ๋ฉฐ ๋ต์ ์ฐพ์ผ๋ฏ๋ก,
16
+ O(N)์ ์๊ฐ๋ณต์ก๋๊ฐ ์์๋๋ค.
17
+
18
+ Space Complexity:
19
+ O(N):
20
+ sorted_list์ ์ ๋ ฌ๋ ๋ฐฐ์ด์ ์ ์ฅํ๋ฏ๋ก,
21
+ O(N)์ ๊ณต๊ฐ๋ณต์ก๋๊ฐ ์์๋๋ค.
22
+ """
23
+ sorted_list = []
24
+ while list1 is not None and list2 is not None :
25
+ if list1 .val < list2 .val :
26
+ sorted_list .append (list1 .val )
27
+ list1 = list1 .next
28
+ else :
29
+ sorted_list .append (list2 .val )
30
+ list2 = list2 .next
31
+
32
+ while list1 is not None :
33
+ sorted_list .append (list1 .val )
34
+ list1 = list1 .next
35
+ while list2 is not None :
36
+ sorted_list .append (list2 .val )
37
+ list2 = list2 .next
38
+
39
+ sorted_node = None
40
+ while sorted_list :
41
+ val = sorted_list .pop ()
42
+ sorted_node = ListNode (val , sorted_node )
43
+
44
+ return sorted_node
You canโt perform that action at this time.
0 commit comments