[백준] 11650 좌표 정렬하기 Node.js

Janet·2023년 10월 7일
0

Algorithm

목록 보기
265/314

문제

2차원 평면 위의 점 N개가 주어진다. 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.

출력

첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.

예제 입력 1

5
3 4
1 1
1 -1
2 2
3 3

예제 출력 1

1 -1
1 1
2 2
3 3
3 4

문제풀이

❌ 시간 초과 풀이: console.log() 출력이 반복되어 시간 초과 발생

const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let [N, ...input] = require('fs').readFileSync(filePath).toString().trim().split('\n');
const arr = input.map((v) => v.split(' ').map(Number));
const sorted = arr.sort((a, b) => {
  // x좌표 같으면 y좌표 기준 오름차순 정렬
  if (a[0] === b[0]) return a[1] - b[1];
  // 그렇지 않으면 x좌표 기준 오름차순 정렬
  return a[0] - b[0];
});

// 시간초과 발생 요인
for (const [x, y] of sorted) {
  console.log(`${x} ${y}`);
}

✅ 답안: join()을 활용해서 console.log() 출력을 1번으로 하면 통과

const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let [N, ...input] = require('fs').readFileSync(filePath).toString().trim().split('\n');
const arr = input.map((v) => v.split(' ').map(Number));
const result = arr
  .sort((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]))
  .map((v) => v.join(' '))
  .join('\n');
console.log(result);
profile
😸

0개의 댓글