728x90

😢 시간 초과 때문에 고생한 문제
😊 이 문제 덕분에 sort()의 새로운 방법을 알게 되었다.
시간 초과를 해결하기 위해 가장 중요한 2가지
1. sort() 1번만 사용하기
처음에는 단순하게 x기준 정렬 후 y기준 정렬했기 때문에 sort()가 2번 사용되었다.
하지만, sort( (a, b) => if( a[0] !== b[0] ) { return a[0] - b[0] } return a[1] - b[1] ); 덕분에 sort() 1번만 진행할 수 있었다.
2. console.log() 1번만 사용하기
또한, 시간 초과에서 중요했던 다른 하나는 console.log()출력을 줄이는 것이었다.
forEach를 이용해, results변수에 모든 출력값을 저장한 후 console.log() 단 한 번 출력해주었더니 시간 초과를 해결할 수 있었다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sort Coordinates 1 | |
// For submit | |
// const fs = require('fs'); | |
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n'); | |
// For local test | |
const input = ['7', '1 -1', '3 3', '1 -2', '1 1', '3 -2', '-2 1', '-3 1']; | |
const N = input.shift(); | |
const coordsArr = input.map(coords => | |
coords.split(' ').map(nums => parseInt(nums)) | |
); | |
let results = ''; | |
coordsArr | |
.sort((a, b) => { | |
if (a[0] !== b[0]) { | |
return a[0] - b[0]; | |
} | |
return a[1] - b[1]; | |
}) | |
.forEach(coords => { | |
results += `${coords[0]} ${coords[1]}\n`; | |
}); | |
console.log(results); |
'Algorithm > JavaScript(Node.js)' 카테고리의 다른 글
백준 2751번: 수 정렬하기 2 Node.js(JavaScript) (0) | 2020.02.19 |
---|---|
백준 11651번: 좌표 정렬하기 2 Node.js(JavaScript) (0) | 2020.02.18 |
백준 1427번: 소트인사이드 Node.js(JavaScript) (0) | 2020.02.17 |
백준 2108번: 통계학 Node.js(JavaScript) (0) | 2020.02.16 |
백준 1436번: 영화감독 숌 Node.js(JavaScript) (0) | 2020.02.14 |