有人能看看我的CPP代码吗?它来自于这个问题:https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/我感到非常沮丧,因为虽然我的python代码可以工作,但是我的cpp代码不能像往常一样工作。忧郁:相同的想法,不同的结果。简直快让我疯了。
正确的输出应该是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;
}发布于 2020-06-28 11:39:05
移除其他的
else total += w;应该是
total += w;发布于 2020-06-28 15:13:53
也许,您可以对您的c++解决方案进行更简单的二进制搜索:
#include <vector>
class Solution {
public:
int shipWithinDays(std::vector<int>& weights, int d) {
int lo = 0;
int hi = INT_MAX;
for (int weight : weights) {
lo = max(lo, weight);
}
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
int required = 1;
int cur = 0;
for (int index = 0; index < weights.size() && required <= d; cur += weights[index++])
if (cur + weights[index] > mid) {
cur = 0;
required++;
}
if (required > d) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
};或者使用基本的按位操作:
class Solution {
public:
int shipWithinDays(vector<int> &weights, int d) {
int lo = 0;
int hi = INT_MAX;
for (int weight : weights)
lo = max(lo, weight);
while (lo < hi) {
int mid = lo + ((hi - lo) >> 1);
int required = 1;
int cur = 0;
for (int index = 0; index < weights.size() && required <= d; cur += weights[index++])
if (cur + weights[index] > mid)
cur = 0, required++;
if (required > d)
lo = -~mid;
else
hi = mid;
}
return lo;
}
};同样,python也是这样:
from typing import List
class Solution:
def shipWithinDays(self, weights: List[int], d: int) -> int:
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = lo + ((hi - lo) >> 1) # or mid = (lo + hi) // 2 || mid = lo + (hi - lo) // 2
cur, required = 0, 1
for weight in weights:
if cur + weight > mid:
required += 1
cur = 0
cur += weight
if required > d:
lo = -~mid # simply lo = mid + 1
else:
hi = mid
return lo参考文献
https://stackoverflow.com/questions/62621262
复制相似问题