26. 删除有序数组中的重复项
- 在做了27题后, 这一题也是同样的双指针法, 提交后发现需要考虑传入的数组为空的情况, 所以在遍历之前需要加一个判断
代码:
/*
* @lc app=leetcode.cn id=26 lang=cpp
*
* [26] 删除有序数组中的重复项
*/
// @lc code=start
class Solution
{
public:
int removeDuplicates(vector<int> &nums)
{
int size = nums.size();
// 判断传入数组是否为空
if (!size)
{
return 0;
}
int slow = 0;
for (int fast = 0; fast < size; fast++)
{
if (nums[slow] != nums[fast])
{
nums[++slow] = nums[fast];
}
}
return slow + 1;
}
};
- 时间复杂度:O(n),其中 n 是数组的长度。快指针和慢指针最多各移动 n 次。
- 空间复杂度:O(1), 只需使用常数的额外空间。