리트코드/midium
[리트코드] 875. Koko Eating Bananas - js (이진탐색)
bbeyak
2023. 8. 20. 14:11
반응형
1. 문제
https://leetcode.com/problems/koko-eating-bananas/
Koko Eating Bananas - LeetCode
Can you solve this real interview question? Koko Eating Bananas - Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating sp
leetcode.com
2. 코드
이진 탐색으로 문제 풀 때는 꼭 반올림, 내림 신경써주기!
/**
* @param {number[]} piles
* @param {number} h
* @return {number}
*/
var minEatingSpeed = function(piles, h) {
let low = 1, hi = Math.max(...piles);
while(low < hi){
let mid = Math.floor((low+hi)/2);
let sum = piles.reduce((acc,cur) => acc += Math.ceil(cur/mid),0);
if(sum <= h){
hi = mid;
}else{
low = mid + 1;
}
}
return low;
};
어제 문제랑 비슷해서 이진 탐색 문제인걸 대번에 알았지만, 그래도 내 손으로 처음 완성한 이진 탐색 코드... 뿌듯
반응형