mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-26 10:43:31 +08:00
895 B
895 B
题目地址
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
思路
此题就是O(n)的解法,拼速度的话,也就是剪剪枝 注意题目中:你不需要考虑数组中超出新长度后面的元素。 说明是要对原数组进行操作的
解法
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0; // 别忘记空数组的判断
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < (nums.size() - 1); fastIndex++){
if(nums[fastIndex] != nums[fastIndex + 1]) { // 发现和后一个不相同
nums[++slowIndex] = nums[fastIndex + 1]; //slowIndex = 0 的数据一定是不重复的,所以直接 ++slowIndex
}
}
return slowIndex + 1; //别忘了slowIndex是从0开始的,所以返回slowIndex + 1
}
};