ele*_*fan 0 c++ compiler-errors compilation testcase
这是我试图解决的问题,以及测试我遇到问题的测试用例的解决方案。
#include <iostream>
#include <vector>
#include <unordered_map>
class Solution {
public:
int longestConsecutive(std::vector<int>& nums)
{
std::unordered_map<int, int> seq;
for (auto i : nums)
{
++seq[i];
}
int max{ 0 };
for (auto i : seq)
{
int ans{ 0 };
int x{ i.first };
if (seq[x] > 0)
{
ans = 1;
int p{ x };
int q{ x };
while (seq[p - 1] > 0)
{
--p;
++ans;
}
while (seq[q + 1] > 0)
{
++q;
++ans;
}
}
if (max < ans)
max = ans;
}
return max;
}
};
int main()
{
Solution s;
std::vector<int> nums{ 4,0,-4,-2,2,5,2,0,-8,-8,-8,-8,-1,7,4,5,5,-4,6,6,-3 };
std::cout << s.longestConsecutive(nums);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我在离线编译器(Visualt Studio 中的 Microsoft C++ 编译器)中测试此测试用例时,它显示测试用例为 5(这是绝对正确的)。
然而,在 leetcode 中提交相同的解决方案后,它显示测试用例为 4(这是错误的)。我也尝试在在线 gdb 编译器中测试这个案例,并且这个测试案例也显示为 4。
我的解决方案已经通过了 55/72 例,所以我确信我的算法或答案输出格式没有任何问题。我认为这是leetcode或在线的问题
考虑您的代码(为简洁起见缩短)
for (auto i : seq)
{
int x{ i.first };
if (seq[x] > 0) // okay, will be in the sequence
{
int p{ x };
int q{ x };
while (seq[p - 1] > 0) // p-1 might not be in the map, so insert
{}
while (seq[q + 1] > 0) // q+1 might not be in the map, so insert
{}
}
}
Run Code Online (Sandbox Code Playgroud)
这两个 while 循环都可能导致插入,从而使. 使用的迭代器无效for (auto i : seq)
。因此,你有未定义的行为,并且接近正确结果更多的是偶然。
归档时间: |
|
查看次数: |
702 次 |
最近记录: |