You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 = [0]
Output: [0]
난이도: easy
재귀로 풀이
var mergeTwoLists = function(list1, list2) {
if (!list1 || !list2) {
return list1 || list2;
}
let node;
if (list1.val < list2.val) {
node = list1;
node.next = mergeTwoLists(list1.next, list2);
} else {
node = list2;
node.next = mergeTwoLists(list1, list2.next);
}
return node;
};
list1과 list2중 남아있는 것이 있다면 나머지를 전부 return하도록 하고,
새롭게 생성할 node에는 list1과 list2의 현재 value를 비교하여 넣어주도록
효율이 그렇게 좋진않은데, 아직 medium도 좀 어렵다... 어떻게 더 효율적으로 할 수 있을지 감이 잘 안잡힌다
'Algorithm' 카테고리의 다른 글
[Leetcode] 509. Fibonacci Number (0) | 2022.03.17 |
---|---|
[Leetcode] 2176.Count Equal and Divisible Pairs in an Array (0) | 2022.03.12 |
[Leetcode] 442. Find All Duplicates in an Array (0) | 2022.03.07 |
[Leetcode] 2144. Minimum Cost of Buying Candies With Discount (0) | 2022.03.07 |
[Leetcode] 1160. Find Words That Can Be Formed by Characters (0) | 2022.03.06 |