有人可以看看我的CPP代码吗?
是因为这个问题:https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
尽管我的python代码有效,但我感到非常沮丧,因为我的cpp代码不能一如既往地工作。 :pensive:相同的想法,不同的结果。它让我疯狂。
正确的输出应该是15
。
我的Python代码返回正确的输出15
,而我的CPP代码返回错误的输出10
。
我的python代码:
def cnt_days(weights, k):
total, cnt = 0, 1
for w in weights:
if total + w > k:
total = 0
cnt += 1
total += w
print(total, cnt)
return cnt
def shipWithinDays(weights, D):
left = max(weights)
right = max(weights) * len(weights) // D + 1
while left < right:
mid = left + (right - left) // 2
if cnt_days(weights, mid) > D:
left = mid + 1
else:
right = mid
return left
if __name__ == "__main__":
print(shipWithinDays([1,2,3,4,5,6,7,8,9,10], 5))
我的cpp代码:#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int cnt_days(vector<int>& weights, int K)
{
int total = 0, cnt = 1;
for (int w: weights)
{
if (total + w > K)
{
total = 0;
cnt++;
}
else total += w;
}
cout << total <<" "<< cnt << endl;
return cnt;
}
int shipWithinDays(vector<int>& weights, int D)
{
int maximum = *max_element(weights.begin(), weights.end());
int left = maximum;
int right = maximum * weights.size() / D + 1;
while (left < right)
{
int mid = left + (right - left)/2;
if (cnt_days(weights, mid) > D)
left = mid + 1;
else
right = mid;
}
return left;
}
int main()
{
vector<int> weights = {1,2,3,4,5,6,7,8,9,10};
int D = 5;
cout << shipWithinDays(weights, D) << endl;
return 0;
}
最佳答案
删除其他
else total += w;
应该total += w;
关于c++ - LeetCode1011。二进制搜索,C++和Python的思想相同,但输出不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62621262/