Skip to content

Commit e57df08

Browse files
committed
merge two sorted lists solution
1 parent 03ded85 commit e57df08

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} list1
10+
* @param {ListNode} list2
11+
* @return {ListNode}
12+
*/
13+
var mergeTwoLists = function (list1, list2) {
14+
// ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋น„์—ˆ์„ ๋•Œ ๋‹ค๋ฅธ ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜
15+
if (list1 === null) return list2;
16+
if (list2 === null) return list1;
17+
18+
// ์ž‘์€ ๊ฐ’ ๊ฐ€์ง„ ๋…ธ๋“œ ์„ ํƒํ•˜๊ณ  ์žฌ๊ท€ํ˜ธ์ถœ
19+
if (list1.val <= list2.val) {
20+
list1.next = mergeTwoLists(list1.next, list2);
21+
return list1;
22+
} else {
23+
list2.next = mergeTwoLists(list1, list2.next);
24+
return list2;
25+
}
26+
};
27+
28+
// ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n1+n2)
29+
// ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)

0 commit comments

Comments
ย (0)