undefined
[백준] 다음 순열 10972번 - Javascript / Node.js 본문
반응형
문제 설명

문제 풀이
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(' '));
}
};
배운 점
반응형
'Coding Test' 카테고리의 다른 글
[백준 - node.js] 1, 2, 3 더하기 9095번 (0) | 2022.09.22 |
---|---|
[백준 - node.js] 외판원 순회2 10971번 (1) | 2022.09.21 |
[백준] 후위 표기식2 1935번 - Javascript / Node.js (0) | 2022.09.08 |
[백준] 2559 수열 - Node/js (0) | 2022.07.29 |
[백준] 3273 두 수의 합 - Node/Js (0) | 2022.07.29 |