๋ฌธ์
ํ์ด ๊ณผ์
์ฐ๊ฒฐ ๋ฆฌ์คํธ์์ ์ค๊ฐ ์์น์ ๊ฐ์ ์ฐพ๋ ๋ฌธ์ ์
๋๋ค.
๋ณ๋์ ์๊ณ ๋ฆฌ์ฆ์ ์๊ตฌํ๋ ๊ฒ์ด ์๋ ๋จ์ ๊ตฌํ
๋ฌธ์ ๋ก ๋ฆฌ์คํธ์ 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 |
๐ฌ ๋๊ธ