const initHash = (num) => {
const hash = {};
for (let i = 1; i <= num; i++) {
hash[i] = 1;
}
return hash;
};
const solution = (n, lost, reserve) => {
const hashTable = initHash(n);
lost.forEach((num) => {
hashTable[num]--;
});
reserve.forEach((num) => {
hashTable[num]++;
});
const whoNeedsHelp = Object.entries(hashTable)
.filter(([key, value]) => value == 0)
.map(([key, value]) => parseInt(key));
whoNeedsHelp.forEach((num) => {
if (hashTable[num - 1] == 2) {
hashTable[num - 1]--;
hashTable[num]++;
} else if (hashTable[num + 1] == 2) {
hashTable[num + 1]--;
hashTable[num]++;
}
});
const filteredResult = Object.values(hashTable).filter((value) => value);
return filteredResult.length;
};
탐욕법이 뭘까...
딱히 코멘트할 것이 없는 것 같다
function solution(n, lost, reserve) {
const list = new Array(n).fill(1);
lost.forEach((nth) => {
list[nth - 1]--;
});
reserve.forEach((nth) => {
list[nth - 1]++;
});
for (let i = 0; i < n; i++) {
if (list[i] == 0) {
if (list[i - 1] == 2) {
list[i - 1]--;
list[i]++;
continue;
}
if (list[i + 1] == 2) {
list[i + 1]--;
list[i]++;
continue;
}
}
}
return list.filter((num) => num > 0).length;
}