Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions raejun/MoveZeroes.js
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

splice는 매번 배열을 당겨와야하기 때문에 비용이 커진다고 하네요!
저도 문제 딱 보고 투포인터를 먼저 떠올리기는 어렵더라고요ㅠ 그리고 암기식으로 하다보니 투포인터는 left, right 선언하고 둘 다 움직이며 swap 하는 형태 라고 외웠는데 또 이렇게 유형 바뀌니까 뭐지 싶고ㅠ

Original file line number Diff line number Diff line change
@@ -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;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 얼리 리턴 좋네요!


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으로 채워주면 되는 방식이었다. 너무 어렵게 생각했던 것 같다.
*/
44 changes: 44 additions & 0 deletions raejun/PalindromeLinkedList.js
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이해하기도 쉽고, 코드도 깔끔하게 잘 작성하신 것 같아요!
효율적인 풀이는 slow/fast 포인터와 reverse를 이용해서 O(1) 추가 공간으로 푸는 것 이라고 하네요ㅠ 하지만 저도 실패

Original file line number Diff line number Diff line change
@@ -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)인 풀이는 떠오르지 않아서, 풀이하지 못했다.
*/
Loading