[JS] 백준 2562. 최댓값

n-u·2022년 6월 27일
0

Algorithm

목록 보기
21/33
post-thumbnail

백준 2562. 최댓값

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

제출한 풀이

  1. 입력 받는 값은 배열로 만든다.
  2. input의 배열을 복사한다.(깊은 복사를 해서 원본 배열이 바뀌지 않도록 한다.)
  3. sort()를 이용해서 배열을 오름차순으로 정렬한다.
  4. 출력(원배열에서 최대값의 인덱스를 찾는다.)
//1
let input = fs.readFileSync(file).toString().split('\n').map(Number);
//2
let cloneInput = [...input];

//3
cloneInput.sort((a, b) => b - a);
//4
console.log(cloneInput[0]);
console.log(input.indexOf(cloneInput[0]) + 1);

풀면서 알게 된 것

  • indexOf()은 0부터 시작한다. (인덱스이므로!)
  • 배열을 가지고 있는 변수를 다른 변수에 할당할 경우, 얕은 복사?가 일어나는 것 같다.
    -> 콘솔에 찍었을때 배열의 순서가 바뀌였었다.
  • 변하기 않은 배열을 만들기 위해 spread문법을 이용해서 깊은 복사를 해서 사용했다.




Reference

https://developer-talk.tistory.com/159
https://bbaktaeho-95.tistory.com/40

profile
기록하며 발전하는 삶

0개의 댓글