[백준] 10818번 최소, 최대

sarang_daddy·2023년 2월 22일
0

백준 10818번

문제 링크

분류

구현(implementation), 수학(math)

문제 설명

N개의 정수가 주어진다. 이때, 최솟값과 최댓값을 구하는 프로그램을 작성하시오.

입력

첫째 줄에 정수의 개수 N (1 ≤ N ≤ 1,000,000)이 주어진다. 둘째 줄에는 N개의 정수를 공백으로 구분해서 주어진다. 모든 정수는 -1,000,000보다 크거나 같고, 1,000,000보다 작거나 같은 정수이다.

출력

첫째 줄에 주어진 정수 N개의 최솟값과 최댓값을 공백으로 구분해 출력한다.

풀이 1

const fs = require("fs");
const path = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
const input = fs
  .readFileSync(path)
  .toString()
  .trim()
  .split("\n")
  .map((el) => el.split(" "));

const N = input[1];

const answer = N.map(Number).reduce(
  (acc, cur) => {
    if (cur < acc[0]) {
      acc[0] = cur;
    } else if (cur > acc[1]) {
      acc[1] = cur;
    }
    return acc;
  },
  [N[0], N[0]]
);

console.log(answer.join(" "));
  • reduce를 연습하고자 사용했다.
  • input으로 받아온 배열은 문자 타입이라 int타입으로 바꾸는게 중요하다.
  • 문자열로 최소 최대를 비교하면 잘못된 결과가 나온다.

풀이2

const fs = require("fs");
const path = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
const input = fs
  .readFileSync(path)
  .toString()
  .trim()
  .split("\n")
  .map((el) => el.split(" "));

const T = Number(input[0]);
const N = input[1].sort((a, b) => a - b);
const answer = [];
answer.push(N[0]);
answer.push(N[T - 1]);

console.log(answer.join(" "));
  • reduce 속도 결과값이 느린거 같아서 sort를 이용해봤다.
  • 결과는 sort가 더 느리다..

풀이3

const fs = require("fs");
const path = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
const input = fs
  .readFileSync(path)
  .toString()
  .trim()
  .split("\n")
  .map((el) => el.split(" "));

const N = input[1].map(Number);

const min = Math.min.apply(null, N);
const max = Math.max.apply(null, N);

console.log(`${min} ${max}`);
  • Math.min과 Math.max를 사용해보자.
  • 코드는 확실히 간결한데.. 과연...!
  • reduce와 비슷했다.

풀이4

const fs = require("fs");
const path = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
const input = fs
  .readFileSync(path)
  .toString()
  .trim()
  .split("\n")
  .map((el) => el.split(" "));

const N = input[1];

const min = Math.min(...N);
const max = Math.max(...N);

console.log(`${min} ${max}`);
  • apply()가 아닌 스프레드를 쓰면 어떨까?
  • 결과는 비슷했다.

추가 학습 apply()

apply() 메서드는 주어진 this 값과 배열 (또는 유사 배열 객체) 로 제공되는 arguments 로 함수를 호출합니다.

const numbers = [5, 6, 2, 3, 7];

const max = Math.max.apply(null, numbers);

console.log(max);
// Expected output: 7

const min = Math.min.apply(null, numbers);

console.log(min);
// Expected output: 2

배열 붙이기

var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

Function.prototype.apply()

profile
한 발자국, 한 걸음 느리더라도 하루하루 발전하는 삶을 살자.

0개의 댓글