본문 바로가기

자료구조+알고리즘/BOJ

[BOJ-10845_silver4] 큐 (자바스크립트)

https://www.acmicpc.net/problem/10845

 

10845번: 큐

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 

[유형]

- 자료구조

- 큐

 

 

 

 

 

[문제 풀이]

명령어를 판단할 배열요소는 temp에 넣고 

"출력" 명령시 새로운 변수에 넣어준다 한줄에 하나씩 출력해줌!

 

 

 

 

[코드]

 

||❌ 시간초과 난 코드

const fs = require('fs');
let [n, ...input] = fs.readFileSync('./input.txt').toString().trim().split('\n');
let temp = [];
let ans = [];
for(command of input){
  let cmd = command.split(' ')[0];
  let cmdCount = command.split(' ')[1];

  if(cmd === 'push'){
    temp.push(Number(cmdCount))
  }else if(cmd === 'front'){
    ans.push(temp[0] ? temp[0] : -1);
  }else if(cmd === 'back'){
    ans.push(temp.length !== 0 ? temp[temp.length-1] : -1);
  }else if(cmd === 'size'){
    ans.push(temp.length)
  }else if(cmd === 'empty'){
    ans.push(temp.length === 0 ? 1 : 0)
  }else if(cmd === 'pop'){
    ans.push(temp.length !== 0? temp.shift() : -1);
  }else return
}

for (let i = 0; i < ans.length; i++) {
  console.log(ans[i]);
}

 

원인 => 0.5초 문제인데 for 문을 2번이나 돌려서 인듯 ㅠ

방법 => ans 에 담기는 데이터들을 배열에 넣지말고 string 으로 넣자 + '\n' 띄어쓰기도 같이 넣어준다.

 

 

||⭕️ 통과된 코드

const fs = require('fs');
let [n, ...input] = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
let temp = [];
let ans = '';
for(command of input){
  let cmd = command.split(' ')[0];
  let cmdCount = command.split(' ')[1];

  if(cmd === 'push'){
    temp.push(Number(cmdCount))
  }else if(cmd === 'front'){
    ans += (temp[0] ? temp[0]+'\n' : -1+'\n');
  }else if(cmd === 'back'){
    ans +=(temp.length !== 0 ? temp[temp.length-1]+'\n' : -1+'\n');
  }else if(cmd === 'size'){
    ans +=(temp.length+'\n')
  }else if(cmd === 'empty'){
    ans +=(temp.length === 0 ? 1+'\n' : 0+'\n')
  }else if(cmd === 'pop'){
    ans +=(temp.length !== 0? temp.shift()+'\n' : -1+'\n');
  }else return
}
console.log(ans.trim());
728x90
반응형