๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 876 - Middle of the Linked List (Easy)

by HandHand 2021. 3. 2.

๋ฌธ์ œ

LeetCode - 876๋ฒˆ

ํ’€์ด ๊ณผ์ •

์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์—์„œ ์ค‘๊ฐ„ ์œ„์น˜์˜ ๊ฐ’์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋ณ„๋„์˜ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์š”๊ตฌํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ ๋‹จ์ˆœ ๊ตฌํ˜„ ๋ฌธ์ œ๋กœ ๋ฆฌ์ŠคํŠธ์˜ head ๋ถ€ํ„ฐ ํฌ์ธํ„ฐ๋ฅผ ์˜ฎ๊ฒจ๊ฐ€๋ฉฐ
๋ฆฌ์ŠคํŠธ์˜ ํฌ๊ธฐ๋ฅผ ๊ตฌํ•œ ๋’ค ์ค‘๊ฐ„ ์œ„์น˜๋ฅผ ๊ณ„์‚ฐํ•˜์—ฌ ๊ตฌํ–ˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var middleNode = function (head) {
  // ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ์˜ ํฌ๊ธฐ ์•Œ์•„๋‚ด๊ธฐ
  let length = 0;
  for (let cur = head; cur; cur = cur.next) {
    length += 1;
  }

  // ํƒ€๊ฒŸ ๋…ธ๋“œ ์ฐพ๊ธฐ
  let cur = head;
  const target = length % 2 === 0 ? length / 2 : Math.floor(length / 2);
  for (let i = 0; i < target; i++) {
    cur = cur.next;
  }

  return cur;
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 121 - Best Time to Buy and Sell Stock (Easy)  (0) 2021.03.02
LeetCode 101 - Symmetric Tree (Easy)  (0) 2021.03.02
LeetCode 221 - Maximal Square (Medium)  (0) 2021.03.02
LeetCode 543 - Diameter of Binary Tree (Easy)  (1) 2021.03.02
LeetCode 283 - Move Zeroes (Medium)  (0) 2021.03.02

๐Ÿ’ฌ ๋Œ“๊ธ€