Js code 및 함수 Tip
만약 디버깅 중 이 부분을 거쳐가는지 궁금하다면
return 1111;
찍어보면 빠르게 알수있음
var oldArr = ["1", "2", "3", "4"]; var newArr = oldArr.map(Number); 다음과 같이 map 메소드로 Number 함수를 각 원소마다 실행시켜주면 된다. Number 함수는 문자를 숫자로 바꿔주는 함수이다.
시간복잡도 문제 해결
배열의 맨 앞 원소를 제거할때 shift쓰면 시간복잡도 O(n)되서 효율성테스트 광탈함.
이 때, 연결리스트(객체)로 큐를 규현하면 깔끔하게 O(1)로 끝내서 통과할 수 있다.
라이브 서버 자동 새로고침 명령어 (nodemon)
npx nodemon app
Javascript로 큐 Class 구현하기
class Queue {
constructor() {
this.elements = {};
this.head = 0;
this.tail = 0;
}
enqueue(element) {
this.elements[this.tail] = element;
this.tail++;
}
dequeue() {
const item = this.elements[this.head];
delete this.elements[this.head];
this.head++;
return item;
}
peek() {
return this.elements[this.head];
}
get length() {
return this.tail - this.head;
}
get isEmpty() {
return this.length === 0;
}
}
Queue 메인문 선언
let q = new Queue();
Or
let queue = new Queue();
Javascript로 스택 Class 선언
class Stack {
constructor() {
this.arr = [];
this.index = 0;
}
push(item) {
this.arr[this.index++] = item;
}
pop() {
if (this.index <= 0) return null;
const result = this.arr[--this.index];
return result;
}
}
Stack 메인문 선언
let stack = new Stack();
배열 대신 힙을 써야 하는 이유
heap(힙)은 완전이진트리(complete binary tree)를 만족하는데 이는 자식노드가 두개 인 조건이 아니라! 그냥 왼쪽부터 차곡차곡 쌓았으면 완전이진트리이다.
deque는 list와 다르게 맨 앞 요소나 맨 뒤의 요소를 pop하는데 O(1)이다.
list는 맨앞의 요소를 pop 하려면 배열을 모두 복사하는 과정이 있으므로 O(n)이 걸려서 타임 에러가 발생할 수 있다.