Open ericagong opened 1 year ago
O(NlogN)
O(2MlogN)
const fs = require("fs");
const inputs = fs.readFileSync("/dev/stdin").toString().split("\n");
const N = Number(inputs.shift()); const cards = inputs.shift().split(" ").map(Number); const M = Number(inputs.shift()); const nums = inputs.shift().split(" ").map(Number);
function lowerBound(arr, val, s, e) {
while (s < e) {
const m = parseInt((s + e) / 2);
if (arr[m] >= val) e = m;
else s = m + 1;
}
// console.log(lowerBound: ${e}
)
return e;
}
function upperBound(arr, val, s, e) {
while (s < e) {
const m = parseInt((s + e) / 2);
if (arr[m] > val) e = m;
else s = m + 1;
}
// console.log(upperBound: ${e}
)
return e;
}
function countByRange(arr, leftVal, rightVal) { const leftIdx = lowerBound(arr, leftVal, 0, arr.length); const rightIdx = upperBound(arr, rightVal, 0, arr.length); return rightIdx - leftIdx; }
// 정렬 함수 필수 cards.sort((a, b) => a - b);
const counts = []; nums.forEach((num) => { counts.push(countByRange(cards, num, num)); });
console.log(counts.join(" "));
⭐ 성찰
function upperBound(arr, val, s, e) { while (s < e) { const m = parseInt((s + e) / 2); if (arr[m] > val) e = m; else s = m + 1; } // console.log(
upperBound: ${e}
) return e; }function countByRange(arr, leftVal, rightVal) { const leftIdx = lowerBound(arr, leftVal, 0, arr.length); const rightIdx = upperBound(arr, rightVal, 0, arr.length); return rightIdx - leftIdx; }