[boj] 2470. 두 용액 (node.js)

호이·2022년 2월 13일
0

algorithm

목록 보기
22/77
post-thumbnail

문제 요약

[boj] 2470. 두 용액 (node.js)

  • 주어진 숫자들 중 서로 다른 두 개를 조건에 맞게 출력하는 문제
  • 조건: 합이 0이거나 0에 가장 가까운 조합 찾기

풀이

  • 일반적으로 이분 탐색으로 조건(최소 거리 갱신)과 L, R을 통해 풀이했던 2470번 문제를
  • 또 다른 풀이법인 두 포인터를 활용해 풀이하였다.

내 풀이

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let cnt = 0;
const input = () => stdin[cnt++];

let stdin = [];
rl.on("line", function (line) {
  stdin.push(line);
}).on("close", function () {
  const N = input();
  const arr = input().split(" ").map(Number);
  let L = 0,
    R = N - 1;
  let sum = Infinity;
  let result = [];
  arr.sort((a, b) => a - b);

  while (L < R) {
    const temp = arr[L] + arr[R];
    if (Math.abs(temp) < sum) {
      sum = Math.abs(temp);
      result = [arr[L], arr[R]];
    }
    temp < 0 ? L++ : R--;
    if (temp == 0) break;
  }
  result.sort((a, b) => a - b);
  console.log(result.join(" "));
  process.exit();
});
  • 합이 0이거나 그에 가장 가까운 경우를 출력해야 하므로, arr[L] + arr[R]을 매번 확인하여 L, R을 갱신해주었다.
  • 문제 알고리즘 구현도 중요하지만 let sum = Infinity; 부분을 실수하여 여러 번 다시 풀었다. 문제의 sum은 두 수의 합이니 최댓값 * 2, 즉 Infinity 로 설정해 두는 것이 안전하다.
profile
매일 부활하는 개복치

0개의 댓글