From c758e8f2ed7c686bc755724aa5793d3359568615 Mon Sep 17 00:00:00 2001 From: raejun92 Date: Thu, 2 Apr 2026 23:04:43 +0900 Subject: [PATCH] feat(raejun): add Move Zeroes, Palindrome Linked List solutions --- raejun/MoveZeroes.js | 36 ++++++++++++++++++++++++++++ raejun/PalindromeLinkedList.js | 44 ++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 raejun/MoveZeroes.js create mode 100644 raejun/PalindromeLinkedList.js diff --git a/raejun/MoveZeroes.js b/raejun/MoveZeroes.js new file mode 100644 index 0000000..230f018 --- /dev/null +++ b/raejun/MoveZeroes.js @@ -0,0 +1,36 @@ +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var moveZeroes = function (nums) { + if (nums.length === 1) return nums; + + if (nums.every((num) => num === 0)) return nums; + + const len = nums.length; + + for (let i = 0; i < len; i++) { + if (nums[i] === 0) { + nums.splice(i, 1); + nums.push(0); + i--; + } + } + + return nums; +}; + +/* +풀지 못함. + +시간 복잡도는 O(n)이다. +공간 복잡도는 O(1)이다. + +배열을 순회하면서 0이 나오면, 해당 인덱스의 요소를 제거하고, 배열의 끝에 0을 추가했다. +처음에, 0이 나올 때마다 0을 제거하고, 배열의 끝에 0을 추가하는 방식으로 풀이하려고 했는데, splice로 요소를 제거할 때마다 배열의 길이가 줄어들어서, 인덱스가 꼬이는 문제가 발생했다. +그래서, i--를 통해 인덱스를 조정하는 방식으로 풀이했다. + +해당 문제 풀이는 시간 초과가 발생했다. +풀이를 찾아보니 투 포인터 방식을 사용해서 풀이하는 방식이 있었다. +0이 아닌 값을 앞에서부터 채우고, 나머지를 0으로 채워주면 되는 방식이었다. 너무 어렵게 생각했던 것 같다. +*/ diff --git a/raejun/PalindromeLinkedList.js b/raejun/PalindromeLinkedList.js new file mode 100644 index 0000000..5904b01 --- /dev/null +++ b/raejun/PalindromeLinkedList.js @@ -0,0 +1,44 @@ +/** + * 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 {boolean} + */ +var isPalindrome = function (head) { + const arr = []; + + while (head) { + arr.push(head.val); + + head = head.next; + } + + const len = arr.length - 1; + + for (let i = 0; i <= len / 2; i++) { + if (arr[i] !== arr[len - i]) return false; + } + + return true; +}; + +/* +14분 걸림. + +시간 복잡도는 O(n)이다. +공간 복잡도는 O(n)이다. + +링크드 리스트를 순회하면서 노드의 값을 배열에 저장했다. +그 다음에, 배열의 길이의 절반까지만 루프를 돌면서, i번째 값과 len - i번째 값을 비교했다. +만약 두 값이 다르면 false를 반환했다. +루프가 끝난 후에는 true를 반환했다. + +처음에 set을 통해 구하려고 했다. +처음 나오는 건 set 에 추가하고, 다음에 나오는 건 set에서 제거하는 방식으로 풀이하려고 했는데, 순서를 고려하지 않아서 실패했다. +시간 복잡도가 O(1)인 풀이는 떠오르지 않아서, 풀이하지 못했다. +*/