使用O(1)空间,O(n)时间复杂度 去除有序数组中的重复数字 C++
int removeDuplicates(vector<int> &nums)
{
int len = sizeof(nums) / sizeof(int);
if (len == 0)
return 0;
int slow = 0, fast = 0;
while (fast < len)
{
if (nums[fast] != nums[slow])
{
slow++;
nums[slow] = nums[fast];
}
fast++;
}
return slow+1;
}
测试代码
int nums1[5] = { 1,2,2,4,4 };
vector<int> nums;
for (int i = 0; i < 5; i++)
nums.push_back(nums1[i]);
int a = removeDuplicates(nums);
cout << a << endl;