FrontEnd :-)

[LeetCode-JS] Merge Two Sorted Lists 본문

JavaScript/Algorithm

[LeetCode-JS] Merge Two Sorted Lists

code10 2022. 12. 15. 18:18

🙋 문제: Merge Two Sorted Lists

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]

 

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

🅰️ 풀이: 

>> 배열이라면 아래와 같이 했겠지만~ 주어진 건 링크드 리스트

return list1.concat(list2).sort() //배열이 아니라서 concat 적용 안됨.

리스트는 어떻게 다뤄야 하나.. 잘 모르겠어서 검색..

 

 다른 사람 풀이:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
    if(!list1) return list2;
    if(!list2) return list1;
    if(list1.val < list2.val){
        list1.next = mergeTwoLists(list1.next, list2);
        return list1;
    } else {
        list2.next = mergeTwoLists(list1, list2.next);
        return list2;
    }
};

>> 재귀를 이용한 방법.

list1 또는 list2가 null인 경우, 다른 리스트를 리턴한다. 아래와 같이 한 줄로 줄일 수 있음. (하지만, 이 경우, 굳이..?)

if(!list1 || !list2) return list1 ? list1 : list2 ;

list1.val이 list2의 값보다 작으면, list1.next는 list1.next과 list2를 비교하고 ... 반대의 경우도 똑같이 비교하면서 ... list1 또는 list2에 계속 merge하다가 최종 반환.

var mergeTwoLists = function(list1, list2) {
	const dummy = new ListNode(-Infinity);
    let prev = dummy;

    while(list1 && list2){
        if(list1.val <= list2.val){
            prev.next = list1;
            prev = list1;
            list1 = list1.next;
        } else {
            prev.next = list2;
            prev = list2;
            list2 = list2.next;
        }
    }
    if(!list1) prev.next = list2;
    if(!list2) prev.next = list1;

    return dummy.next;
};

>> 새 ListNode를 만들어 담는 방법. 

 

 

https://duncan-mcardle.medium.com/leetcode-problem-21-merge-two-sorted-lists-javascript-b5a4de3da319

 

LeetCode problem #21–Merge two sorted lists (JavaScript)

In this LeetCode challenge, we’re given two sorted LinkedLists, and asked to merge them in order. So, given two LinkedLists with the…

duncan-mcardle.medium.com

 

'JavaScript > Algorithm' 카테고리의 다른 글

programmers 분수의 덧셈  (0) 2023.03.08
programmers 옹알이 (1)  (0) 2023.03.07
[LeetCode-JS] Valid Parentheses  (0) 2022.12.10
[LeetCode-JS] Longest Common Prefix  (0) 2022.12.09
[LeetCode-JS] Roman to Integer  (0) 2022.12.08
Comments