반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

undefined

[백준] 다음 순열 10972번 - Javascript / Node.js 본문

Coding Test

[백준] 다음 순열 10972번 - Javascript / Node.js

JavaScripter 2022. 9. 11. 23:07
반응형

문제 설명


문제 풀이

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

let input = [];
let n = 0;
let count = 0;

rl.on('line', function (line) {
  if (!count) {
    n = +line;
  } else {
    input = line.split(' ').map(e => +e);
  }
  count++;
}).on('close', function () {
  solution(input);
  process.exit();
});

const solution = input => {
  let sorted = [...input].sort((a, b) => b - a);
  let a = 0;
  let b = 0;
  let arr = [];

  // 내림차순이라면 마지막 요소이기 때문에 -1 리턴
  if (sorted.every((v, i) => v === input[i])) {
    console.log(-1);
  } else {
    // a 값구하기 (바꿔줄 인덱스)
    for (let i = input.length - 1; i >= 0; i--) {
      if (input[i - 1] < input[i]) {
        a = i - 1;
        break;
      }
    }
    // b 값구하기 (바꿔줄 인덱스)
    for (let j = a + 1; j < input.length; j++) {
      if (input[j] > input[a]) {
        arr.push(input[j]);
      }
    }
    // b보다 큰 값중 가장 작은 값
    b = input.indexOf(Math.min(...arr));

    // 스왑
    [input[a], input[b]] = [input[b], input[a]];

    // 뒷부분 오름차순 정렬
    let pre = input.slice(0, a + 1);
    let suf = input.slice(a + 1, input.length).sort((a, b) => a - b);
    console.log(pre.concat(suf).join(' '));
  }
};

 


배운 점

반응형
Comments