알고리즘
프로그래머스
- Level 1 체육복
function solution(n, lost, reserve) {
const newLost = lost.filter(element => reserve.includes(element) === false).sort((a, b) => a - b);
const newReserve = reserve.filter(element => lost.includes(element) === false).sort((a, b) => a - b);
newReserve.forEach((element) => {
let index1;
let index2;
if ((index1 = newLost.indexOf(element - 1)) !== -1) {
newLost.splice(index1, 1);
return;
}
if ((index2 = newLost.indexOf(element + 1)) !== -1) {
newLost.splice(index2, 1);
return;
}
})
return n - newLost.length;
}
- Level 2 가장 큰 수
function solution(numbers) {
let newNumbers = [...numbers].map(element => String(element));
newNumbers.sort((a, b) => (b + a) - (a + b));
if (newNumbers[0] === '0') {
return '0';
}
return newNumbers.join('');
}
- Level 2 가장 큰 정사각형 찾기
function solution(board) {
let maxValue = 0;
const dp = new Array();
dp.push(new Array(board[0].length + 1).fill(0));
board.forEach((element) => {
element.unshift(0);
dp.push(element);
})
for (let i = 1; i < dp.length; i++) {
for (let j = 1; j < dp[0].length; j++) {
if (dp[i][j] !== 0) {
dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1;
if (maxValue < dp[i][j]) {
maxValue = dp[i][j];
}
}
}
}
return maxValue * maxValue;
}
- Level 1 최대공약수와 최소공배수
function solution(n, m) {
const realN = n;
const realM = m;
let GCD;
let LCM;
while (n !== 0 && m !== 0) {
if (n > m) {
n %= m;
continue;
}
if (m > n) {
m %= n;
continue;
}
}
n === 0 ? GCD = m : GCD = n;
LCM = realN * realM / GCD;
return [GCD, LCM];
}
- Level 1 완주하지 못한 선수
function solution(participant, completion) {
const hash = new Object();
participant.forEach((element) => {
if (hash[element] === undefined) {
hash[element] = 0;
}
hash[element] += 1;
})
completion.forEach((element) => {
hash[element] -= 1;
})
for (let key of Object.keys(hash)) {
if (hash[key] !== 0) {
return key;
}
}
}
- Level 1 예산
function solution(d, budget) {
let count = 0;
let current = 0;
const newD = [...d];
newD.sort((a, b) => a - b);
newD.forEach((element) => {
if (current + element <= budget) {
current += element;
count += 1;
}
})
return count;
}