I tried writing a function that removes duplicates from an ordered array and returns the number of distinct duplicates. In fact, this is question 26 in leetcode. Here’s an inline link to leetcode.
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n=0;
int i=0;
while(i<nums.size()){
int j=i+1;
while(nums[j]==nums[i]){
j++;
}
nums[n]=nums[i];
n++;
i=j;
}
return n;
}
};
I don’t know why this error happens, I hope you can help me find and resolve this runtime error, thanks.
>Solution :
In the while loop, you have while (nums[j] == nums[i]). However, you don’t actually check if j is a valid index of nums – i.e. if j doesn’t go outside the boundaries of nums. Therefore, j could possibly continuously increment until it accesses an element outside the boundaries of nums. Then, when nums[j] == nums[i] is checked, this causes a segmentation fault, which causes the heap buffer overflow.
Try something like
while (j < nums.size() && nums[j] == nums[i])
The code above will first check if j accesses an element outside nums. If it doesn’t, then it will check nums[j] == nums[i]. If it does, the while loop will automatically exit.