#include <iostream>
#include <vector>
using namespace std;
//给定 nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4],
//函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。
//你不需要考虑数组中超出新长度后面的元素
class Solution {
public:
int removeDuplicates(vector<int> &nums) {
if (nums.empty())
{
return 0;
}
//设置快慢两个指针,慢指针(j)始终指向无重复数组的末尾,快指针负责遍历数组-i
int j = 0, n = nums.size();
for (int i = 0; i < n; i++)
{
if (nums[i] != nums[j])
{
nums[++j] = nums[i];//数组中第一个元素和最后一个元素没动
}
}
return j + 1;
}
};
int main()
{
vector<int> nums = { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4 };
int number = nums.size();
for (int i = 0; i < number; i++)
{
cout << nums[i] << " ";
}
Solution solu;
number = solu.removeDuplicates(nums);
cout << "removeDuplicates sums:" << endl;
for (int i = 0; i < number; i++)
{
cout << nums[i] << " ";
}
system("pause");
return 0;
}
[LeetCode] 26Remove Duplicates from Sorted Array 有序数组中去除重复项
最新推荐文章于 2021-08-09 23:58:00 发布