λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 21 - Merge Two Sorted Lists (Easy)

by HandHand 2021. 3. 2.

문제

LeetCode - 21번

풀이 κ³Όμ •

병합 μ •λ ¬ 의 병합 과정을 직접 κ΅¬ν˜„ν•΄λ³΄λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

병합 μ •λ ¬ 은 각각의 λ°°μ—΄ μš”μ†Œλ₯Ό κ· λ“±ν•˜κ²Œ λ‚˜λˆ„κ³  λ‚˜λˆ„μ–΄μ§„ 배열을 μ •λ ¬ν•˜μ—¬ ν•©μΉ˜λŠ” 뢄할정볡 을 μ‚¬μš©ν•˜λŠ” μ •λ ¬ μ•Œκ³ λ¦¬μ¦˜μž…λ‹ˆλ‹€.
두 배열이 λͺ¨λ‘ μ •λ ¬λœ μƒνƒœμ΄κΈ° λ•Œλ¬Έμ— λ°°μ—΄μ˜ κ°€μž₯ μ•ž μš”μ†ŒλΆ€ν„° μ„œλ‘œ 비ꡐ해주며 μž‘μ€ μš”μ†Œλ“€μ„ ν•˜λ‚˜μ”© μΆ”κ°€ν•΄λ‚˜κ°€λ©΄ λ©λ‹ˆλ‹€.

λ§Œμ•½ λ‘˜ 쀑 ν•˜λ‚˜μ˜ 배열이 λΉ„μ–΄μžˆμ„ κ²½μš°μ—λŠ” λΉ„μ–΄μžˆμ§€ μ•Šμ€ 배열을 κ·ΈλŒ€λ‘œ 이어뢙이면 λ©λ‹ˆλ‹€.
μž…λ ₯으둜 λ‘˜ 쀑 ν•œ 배열이 λΉ„μ–΄μžˆλŠ” 것이 μ‘΄μž¬ν•  수 μžˆμœΌλ―€λ‘œ 이 뢀뢄에 λŒ€ν•΄ λ³„λ„μ˜ μ˜ˆμ™Έμ²˜λ¦¬λ₯Ό μ§„ν–‰ν•΄μ€¬μŠ΅λ‹ˆλ‹€.

μ½”λ“œ

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function (l1, l2) {
  let head = null;
  let tail = null;

  if (!l1 || !l2) {
    return l1 ? l1 : l2;
  }

  while (l1 && l2) {
    if (l1.val < l2.val) {
      if (!head) {
        head = new ListNode(l1.val);
        tail = head;
      } else {
        tail.next = new ListNode(l1.val);
        tail = tail.next;
      }

      l1 = l1.next;
    } else {
      if (!head) {
        head = new ListNode(l2.val);
        tail = head;
      } else {
        tail.next = new ListNode(l2.val);
        tail = tail.next;
      }

      l2 = l2.next;
    }
  }

  if (l1) tail.next = l1;
  if (l2) tail.next = l2;

  return head;
};
λ°˜μ‘ν˜•

'πŸƒ algorithm > leetcode' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

LeetCode 322 - Coin Change (Medium)  (0) 2021.03.03
LeetCode 46 - Permutations (Medium)  (0) 2021.03.03
LeetCode 240 - Search a 2D Matrix II (Medium)  (0) 2021.03.02
LeetCode 155 - Min Stack (Easy)  (0) 2021.03.02
LeetCode 39 - Combination Sum (Medium)  (0) 2021.03.02

πŸ’¬ λŒ“κΈ€