Leetcode
medium
binary search
array
python
c++
Learn More →
Learn More →
此題為有n串香蕉,第i串有piles[i]根香蕉
Binary Search二分法變化題:
class Solution(object):
def minEatingSpeed(self, piles, h):
"""
:type piles: List[int]
:type h: int
:rtype: int
"""
#二分搜的變化
#範圍為1與max(piles)之間 大於max肯定不是最慢速度
#二分找適當的速度之下可以全部吃完且滿足時間內
minSpeed=1
maxSpeed=max(piles)
while minSpeed<=maxSpeed:
mid=(minSpeed+maxSpeed)/2
totalHour=0
for val in piles:
carry=0 if val%mid==0 else 1 #餘數需多加1小時
totalHour+=(val/mid)+carry
if totalHour<=h: #吃太快了
maxSpeed=mid-1
else:
minSpeed=mid+1
return minSpeed
class Solution {
public:
int minEatingSpeed(vector<int>& piles, int h) {
int min=1;
int max=*max_element(piles.begin(), piles.end());
while (min<=max){
int mid=min+(max-min)/2;
long long int totalHours=0;
for (auto val: piles){
int carry= (val%mid==0)? 0: 1;
totalHours+=int(val/mid)+carry;
}
if (totalHours<=h)
max=mid-1;
else
min=mid+1;
}
return min;
}
};
###### tags: Leetcode easy python c++ string Top 100 Liked Questions
Aug 21, 2023[題目連結:] https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/ 題目: 解題想法: 此題為給一target目標節點,返回所有跟target相距k步的節點各點值皆不重複 可往上拜訪父點,也可往下拜訪子點 DFS+BFS拜訪 所需工具:dic= collections.defaultdict(list){key:某點的值 ; value:與他相連的所有鄰居的值}
Mar 29, 2023[題目連結:] https://leetcode.com/problems/range-sum-query-immutable/description/ 題目: 解題想法: 此題為設計實做一個NumArray類別,使用sumRange(i, j) 時要能夠回傳[i, j]範圍內的和 prefix sum前綴和想法self.nums紀錄原本的數組 self.sumArray紀錄從頭到nums[i]的和 最終 self.sumArray[right]-self.sumArray[left]+self.nums[left]即為解 ex: nums =[-2, 0, 3, -5, 2, -1]
Mar 29, 2023[題目連結:] https://leetcode.com/problems/nim-game/description/ 題目: 解題想法: 此題目為給n個石頭,你與對手每次可以拿走1~3顆最先拿完的人獲勝 你先開始拿 判斷是否你能獲勝 基本的if else判斷是否為4的倍數即可
Mar 29, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up