26. Remove Duplicates from Sorted Array
我在leetcode上提交它时遇到此运行时错误,它在编码块上工作正常,但在leetcode编译器中显示此错误
924行:字符9:运行时错误:引用绑定(bind)到类型为'int'的空指针(STL_vector.h)
摘要:UndefinedBehaviorSanitizer: undefined 行为/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/STL_vector.h :933:9
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int k=nums[0];
for(auto i=nums.begin()+1;i<nums.end();i++)
{
if(*i==k) nums.erase(i) , i--;
else k=*i;
}
return nums.size();
}
};
有人可以帮助我找到错误的原因吗? 最佳答案
nums
): if (nums.empty()) {
return 0;
}
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
int k = nums[0];
for (auto i = nums.begin() + 1; i < nums.end(); i++) {
if (*i == k) {
nums.erase(i) , i--;
}
else {
k = *i;
}
}
return nums.size();
}
};
size()
编写一个简单的循环。这将传递给LeetCode:// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
// Start
static const struct Solution {
using SizeType = std::uint_fast16_t;
static const int removeDuplicates(
std::vector<int>& nums
) {
const SizeType len = std::size(nums);
SizeType count = 0;
for (SizeType i = 1; i < len; ++i) {
if (nums[i] == nums[i - 1]) {
++count;
} else {
nums[i - count] = nums[i];
}
}
return len - count;
}
};
关于c++ - 从排序的 vector 中删除重复项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63830844/