问题:给定一个排序的数组,将数组去除重复值,不开辟新的空间(即In-place[1])
输入:排序后的数组的引用nums
输出:去重后的数组长度
思想:设去重数组长度length为1
判断数组相邻元素是否一样。不一样,则length加1,并且将当前元素覆盖原数组下标为length的元素。
报错:
错误代码:runtime error: reference binding to null pointer of type 'const value_type' (stl_vector.h)
原因:未考虑传入空数组的情况,nums.size()出错。
改进步骤:加入判断条件,判断数组是否为空。[2]详见下方代码
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int length=1;
if(nums.size()>0)
{
for(int i = 1; i < nums.size(); i++)
{
if(nums[i-1]!=nums[i])
{
nums[length]=nums[i];
length++;
}
}
return length;
}
else
{
return 0;
}
}
};
时间复杂度为O(n)空间复杂度为O(1).比大多数都要慢,占用空间大。
solution:[3]
solution和我的思路一样,T(n)和S(n)应该也一样。
- https://en.wikipedia.org/wiki/In-place_algorithm
- https://blog.csdn.net/m0_38088298/article/details/79249044
- https://leetcode.com/articles/remove-duplicates-from-sorted-array/