leetcode 1011.在 D 天内送达包裹的能力 && 1482. 制作 m 束花所需的最少天数
1011题
int shipWithinDays(vector<int>& weights, int D) {
int day = 1, i;
int s = 0,ma = weights[0], carry;
for(i = 0; i < weights.size(); i++)
{
s += weights[i];
ma = max(ma,weights[i]);
}
int left = ma, right = s, mid;
while(left <= right)
{
carry = 0;//carry每次重新计算清零
mid = (left + right) / 2;
for(i = 0; i < weights.size(); i++)
{
carry += weights[i];
if(carry > mid)//假设mid为当前的运载能力
{
day += 1;
carry = weights[i];
}
}
if(day <= D)
{
right = mid - 1;
day = 1;
}
else
{
left = mid + 1;
day = 1;
}
}
return left;
}
1482题解
bool judge(vector<int>bloomDay, int m, int k, int days)
{
int l = bloomDay.size(), count = 0,tmp = 0;;
vector<int>flag(l,0);
int i, j;
for(i = 0; i < l; i++)
{
if(bloomDay[i] <= days)
flag[i] = 1;
}
for(i = 0; i < l; i++)
{
if(flag[i])
{
tmp++;
if(tmp == k)
{
count++;
tmp = 0;
}
}
else
tmp = 0;
}
if(count >= m)
return true;
return false;
}
int minDays(vector<int>& bloomDay, int m, int k) {
int l = bloomDay.size();
if(m > l / k) return -1;
int i, j, left, right, mid;
int mi = bloomDay[0], ma = bloomDay[0];
for(i = 1; i < l; i++)
{
mi = min(mi,bloomDay[i]);
ma = max(ma,bloomDay[i]);
}
left = mi;
right = ma;
while(left <= right)
{
mid = (left + right) / 2;
if(judge(bloomDay,m,k,mid))
right = mid - 1;
else
left = mid + 1;
}
return left;
}
仅看代码结构的话会发现这两道题还是有很多相似之处的。