![](/img/trans.png)
[英]Why does only one of my return tuple work but is fine when I print it out?
[英]Why does my counter not function properly when it should be 0, but other values >0 work fine?
我正在尝试做的事情
返回一个 integer,它表示我需要添加的数字数量,以便使我的数组连续(一旦排序,首先)。
样本输入和 output
输入:[6,2,3,8]。
Output:3。
原因:将向量排序为 [2, 3, 6, 8] 后,我们需要 3 个数字以使整个向量连续(需要将 4、5、7 添加到数组中,因此返回 3)。
我在哪里?
在向量中处理了 1 integer 的基本情况(返回 0;没有连续的内容)。
创建了一个计数器,设置为 0。
对向量进行排序,升序。
遍历向量,检查:
如果右边的值和当前值的差=1,那么计数器加1,这意味着下一个数字不是连续的。 因此我们需要一个数字。
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdlib>
int makeArrayConsecutive2(std::vector<int> statues) {
if (statues.size() == 1) {
return 0;
}
int counter = 0;
std::sort(statues.begin(), statues.end());
for (int i = 0; i < statues.size(); i++) {
if (statues[i+1] - statues[i] != 1) {
counter += 1;
}
}
return counter;
}
那么问题是什么?
我的 4/5 测试用例通过了,除了这个:
输入:[5, 4, 6] 预期:0 实际:1
我无法理解为什么这不适用于这种情况。 如果其他一切正常,为什么只有这一个案例? 我怀疑它是一个索引问题,但我尝试从我的索引中使用 -1,但仍然无法正常工作。
谢谢您的帮助。
这些是更正后的行:
for (int i = 0; i < statues.size()-1; i++) {
if (statues[i+1] - statues[i] != 1) {
counter += statues[i+1] - statues[i] -1;
}
}
标准库已经提供了std::adjacent_difference
,它可以为您完成绝大多数工作:
#include <numeric>
#include <iostream>
#include <vector>
#include <algorithm>
int makeArrayConsecutive(std::vector<int> input)
{
std::sort(input.begin(), input.end());
std::vector<int> diffs;
std::adjacent_difference(input.begin(), input.end(), std::back_inserter(diffs));
std::transform(diffs.begin(), diffs.end(), diffs.begin(), [](int a) { return a - 1; });
int result = std::accumulate(diffs.begin() + 1, diffs.end(), 0);
return result;
}
int main()
{
std::cout << makeArrayConsecutive({ 6, 2, 3, 8 }) << "\n";
std::cout << makeArrayConsecutive({ 5, 4, 6 });
}
结果(如预期):
3
0
注意:为了清楚起见,我将每个操作分开。 您可以(例如)通过使用带有std::accumulate
的仿函数来很容易地消除std::transform
:
int makeArrayConsecutive(std::vector<int> input)
{
std::sort(input.begin(), input.end());
std::vector<int> diffs;
std::adjacent_difference(input.begin(), input.end(), std::back_inserter(diffs));
int result = std::accumulate(diffs.begin() + 1, diffs.end(),
0,
[](int total, int val) { return total + val - 1; });
return result;
}
同样,您可以通过将差异写回输入数组来消除差异的额外存储,如果输入非常大,这可以大大减少存储需求:
int makeArrayConsecutive(std::vector<int> input)
{
std::sort(input.begin(), input.end());
std::adjacent_difference(input.begin(), input.end(), input.begin());
int result = std::accumulate(input.begin() + 1, input.end(),
0,
[](int total, int val) { return total + val - 1; });
return result;
}
...但是如果您只是想弄清楚发生了什么,我认为第一个版本可能是最容易遵循的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.