|
| 1 | +class ListNode { |
| 2 | + val: number; |
| 3 | + next: ListNode | null; |
| 4 | + constructor(val?: number, next?: ListNode | null) { |
| 5 | + this.val = val === undefined ? 0 : val; |
| 6 | + this.next = next === undefined ? null : next; |
| 7 | + } |
| 8 | +} |
| 9 | + |
| 10 | +/** |
| 11 | + *@link https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ |
| 12 | + * |
| 13 | + * ์ ๊ทผ ๋ฐฉ๋ฒ : |
| 14 | + * - ๋ฆฌ์คํธ ์ํํด์ ๋ฆฌ์คํธ ์ฌ์ด์ฆ ์์๋ธ ๋ค, ์์์๋ถํฐ ๋ช ๋ฒ์งธ ๋
ธ๋๋ฅผ ์ ๊ฑฐํด์ผํ๋์ง ์์๋ด๊ธฐ |
| 15 | + * - ๋ฆฌ์คํธ ๋ค์ ์ํํด์ ํด๋น ์ธ๋ฑ์ค์ ๋
ธ๋ ์ ๊ฑฐํ๊ธฐ |
| 16 | + * |
| 17 | + * ์๊ฐ๋ณต์ก๋ : O(n) |
| 18 | + * - n = ๋ฆฌ์คํธ ๊ธธ์ด |
| 19 | + * - 1ํ ์ํ -> ๋ฆฌ์คํธ ๊ธธ์ด ์์๋ด๊ธฐ, ์ถ๊ฐ๋ก 1ํ ์ํํด์ ๋
ธ๋ ์ ๊ฑฐ |
| 20 | + * |
| 21 | + * ๊ณต๊ฐ๋ณต์ก๋ : O(1) |
| 22 | + * - ๊ณ ์ ๋ ๋ณ์๋ง ์ฌ์ฉ |
| 23 | + */ |
| 24 | +function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { |
| 25 | + let listSize = 0; |
| 26 | + let current = head; |
| 27 | + |
| 28 | + // ๋ฆฌ์คํธ ๊ธธ์ด ๊ตฌํ๊ธฐ |
| 29 | + while (current) { |
| 30 | + listSize++; |
| 31 | + current = current.next; |
| 32 | + } |
| 33 | + |
| 34 | + // ์ ๊ฑฐํ ๋
ธ๋์ ์ธ๋ฑ์ค |
| 35 | + const targetIndex = listSize - n; |
| 36 | + let currentIndex = 0; |
| 37 | + |
| 38 | + current = head; |
| 39 | + |
| 40 | + if (targetIndex === 0) return head ? head.next : null; |
| 41 | + |
| 42 | + while (current) { |
| 43 | + if (currentIndex === targetIndex - 1 && current.next) { |
| 44 | + current.next = current.next.next; |
| 45 | + break; |
| 46 | + } |
| 47 | + currentIndex++; |
| 48 | + current = current.next; |
| 49 | + } |
| 50 | + |
| 51 | + return head; |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * |
| 56 | + * ์ ๊ทผ ๋ฐฉ๋ฒ : two pointer ์ฌ์ฉ |
| 57 | + * - ์ฒซ ๋ฒ์งธ ๋
ธ๋๊ฐ ์ ๊ฑฐ๋๋ ๊ฒฝ์ฐ๊ฐ ์กด์ฌํ๋๊น, dummy ๋
ธ๋ ๋ง๋ค์ด์ ํค๋ ๋
ธ๋๋ก ์ค์ |
| 58 | + * - fast ํฌ์ธํฐ์ ์ด๊ธฐ ์์น๋ฅผ n+1๋ก ์ค์ ํ๊ธฐ |
| 59 | + * - ์ดํ์๋ slow ํฌ์ธํฐ์ fast ํฌ์ธํฐ ๋ชจ๋ 1๊ฐ์ฉ ๋ค์ ๋
ธ๋๋ก ์ํ |
| 60 | + * - fast ํฌ์ธํฐ๊ฐ ๋์ ๋๋ฌํ๋ฉด, slow ํฌ์ธํฐ๋ ์ญ์ ํ ๋
ธ๋ ์ด์ ๋
ธ๋์ ๋๋ฌ |
| 61 | + * |
| 62 | + * ์๊ฐ๋ณต์ก๋ : O(n) |
| 63 | + * - n = ๋ฆฌ์คํธ ๊ธธ์ด |
| 64 | + * - 1ํ ์ํ๋ก ์ญ์ ํ ๋
ธ๋ ์์๋ด๊ธฐ |
| 65 | + * |
| 66 | + * ๊ณต๊ฐ๋ณต์ก๋ : O(1) |
| 67 | + * - ๊ณ ์ ๋ ๋ณ์๋ง ์ฌ์ฉ |
| 68 | + */ |
| 69 | +function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { |
| 70 | + if (head === null) return null; |
| 71 | + |
| 72 | + const dummy = new ListNode(); |
| 73 | + dummy.next = head; |
| 74 | + |
| 75 | + let slow: ListNode | null = dummy, |
| 76 | + fast: ListNode | null = dummy; |
| 77 | + |
| 78 | + // fast ํฌ์ธํธ ์์น n+1์ผ๋ก ์ด๊ธฐ ์ธํ
|
| 79 | + for (let i = 0; i <= n; i++) { |
| 80 | + fast = fast.next!; |
| 81 | + } |
| 82 | + |
| 83 | + while (fast !== null) { |
| 84 | + slow = slow.next!; |
| 85 | + fast = fast.next; |
| 86 | + } |
| 87 | + |
| 88 | + // ๋ค์ ๋
ธ๋ ์ญ์ |
| 89 | + slow.next = slow.next!.next; |
| 90 | + |
| 91 | + return dummy.next; |
| 92 | +} |
0 commit comments