LeetCode删除有序数组重复项II代码平台测试失败原因排查
LeetCode Remove Duplicates from Sorted Array II 代码异常问题
题目说明
我正在解决LeetCode的Remove Duplicates from Sorted Array II问题,要求如下:
- 给定一个非降序排列的整数数组
nums,原地移除部分重复元素 - 每个唯一元素最多保留两次,保持元素相对顺序不变
- 最终结果放在数组前
k个位置,返回k值
实现代码
我编写的C++代码如下:
#include <iostream> #include <bits/stdc++.h> using namespace std; struct getrid { bool operator()(int x) { static int count = 0; static int prev = -1000001; if(count == 0) { prev = x; count++; return false; } else { if(x == prev) { count++; if(count > 2) { return true; } else { return false; } } else { prev=x; count=1; return false; } } } }; class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.size() < 3) { return nums.size(); } auto last_iterator=std::remove_if(nums.begin(),nums.end(),getrid()); if(last_iterator == nums.end()) { std::cout <<"Pointing to iterator pointed by end\n"; } int total_element= last_iterator-nums.begin(); return total_element; } };
异常现象
这段代码在多数测试用例中运行正常,但在LeetCode平台上,输入[1,1]或[1,2,2]这类末尾元素仅出现两次的测试用例时执行失败。不过在在线GDB编译器中运行时,输入[1,1]返回2、输入[1,2,2]返回3,结果完全正确。
在线GDB测试代码如下:
/****************************************************************************** Online C++ Compiler. Code, Compile, Run and Debug C++ program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include <iostream> #include <bits/stdc++.h> using namespace std; struct getrid { bool operator()(int x) { static int count = 0; static int prev = -1000001; if(count == 0) { prev = x; count++; return false; } else { if(x == prev) { count++; if(count > 2) { return true; } else { return false; } } else { prev=x; count=1; return false; } } } }; class Solution { public: int removeDuplicates(vector<int>& nums) { auto last_iterator=std::remove_if(nums.begin(),nums.end(),getrid()); if(last_iterator == nums.end()) { std::cout <<"Pointing to iterator pointed by end\n"; } int total_element= last_iterator-nums.begin(); return total_element; } }; int main() { std::vector<int> vec = {1,2,2}; Solution s; int total_val = s.removeDuplicates(vec); std::cout <<"total val returned is: " << total_val <<"\n"; return 0; }
求助
请问有人能帮忙分析为什么这段代码在LeetCode上测试失败吗?谢谢。
内容的提问来源于stack exchange,提问作者Invictus
相关产品推荐
相关产品推荐

