๐ฅ Algorithm/Baekjoon
[๋ฐฑ์ค 10816๋ฒ] ์ซ์ ์นด๋2 - ์๋ฐ์คํฌ๋ฆฝํธ(nodejs)
Lennon
2022. 2. 3. 19:57
728x90
๋ฐ์ํ
https://www.acmicpc.net/problem/10816
const fs = require('fs');
const input = fs.readFileSync('dev/stdin').toString().trim().split('\n');
const binarySearch = (arr, num) => {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
let middle = Math.floor((start + end) / 2);
if (arr[middle][0] < num) {
start = middle + 1;
} else if (arr[middle][0] > num) {
end = middle - 1;
} else {
return arr[middle][1];
}
}
return 0;
};
const haveCard = input[1]
.split(' ')
.sort((a, b) => a - b)
.map(Number);
const isCard = input[3].split(' ').map(Number);
const arr = [[haveCard[0], 1]];
for (let i = 1; i < haveCard.length; i++) {
if (haveCard[i - 1] === haveCard[i]) {
arr[arr.length - 1][1]++;
} else {
arr.push([haveCard[i], 1]);
}
}
const answer = isCard.map((v) => {
return binarySearch(arr, v);
});
console.log(answer.join(' '));
binarySearch => ์ด๋ถ ํ์ ํจ์
๋จผ์ ๊ฐ์ง๊ณ ์๋ ์ซ์ ์นด๋ ๋ฐฐ์ด์ ์์ ์์๋๋ก ์ ๋ ฌํ๊ณ , ์ค๋ณต๋ ์นด๋ ๊ฐ์๋ฅผ ์ผ๋ค.
๊ทธ ํ binarySearch๋ฅผ ์ด์ฉํด logN ์๊ฐ๋ณต์ก๋๋ก ๋น ๋ฅด๊ฒ ๊ตฌํด์ฃผ๋ฉด ๋!
๊ทธ๋ฅ ๋ฐ๋ณต๋ฌธ์ผ๋ก ๊ตฌํ๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๊ฑธ๋ฆด ๊ฒ์ด๋ค.
728x90
๋ฐ์ํ