# 1. 题目

## 1.1 英文题目

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-placein-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

## 1.3输入输出

| 输入 | 输出 |
| nums = [1,1,2] | 2, nums = [1,2,_] |

| [0,0,1,1,1,2,2,3,3,4] | 5, nums = [0,1,2,3,4,,,,,_] |

IDE：VS2019
IDE版本：16.10.1

# 3. 程序

## 3.1 测试程序

``````#include "Solution.h"
#include <vector>  // std::vector
#include<iostream> // std::cout
using namespace std;

// 主程序
void main()
{
vector<int> nums = { 0,0,0,1,1,1,2,2,3,4,4 }; // 输入
Solution solution; // 实例化Solution
int k = solution.removeDuplicates(nums); // 主功能

// 输出
cout << k << ", [";
for (int i = 0; i < k; i++)
{
if (i == k - 1)
cout << nums[i] << "]";
else
cout << nums[i] << ",";
}
}

``````

## 3.2 功能程序

### 3.2.1 最佳程序

#### （1）代码

``````#pragma once
#include<vector>    // std::vector
using namespace std;

//主功能
class Solution {
public:
int removeDuplicates(vector<int>& nums)
{
if (nums.size() > 1)
{
int i; // i为慢指针，指向的是去重后最后一位，随j更新
int j; // j为快指针，不断向前探索
for (i = 0, j = 0; j < nums.size(); j++)
{
if (nums[i] != nums[j])  // 若快指针所指元素与慢指针相同，则慢的不动，快的前进一步
nums[++i] = nums[j]; // 若不同，则慢的前进一步指向快指针指的元素，快指针继续向前一步
}
return i + 1; // 因为下标从0开始，所以去重后的元素个数为i+1
}
}
};
``````

### 3.2.2 自写程序

#### （1）代码

``````#pragma once
#include<vector>    // std::vector
#include<algorithm> // std::find
using namespace std;

//主功能
class Solution {
public:
int removeDuplicates(vector<int>& nums)
{
if (nums.size() > 1) // 若nums不是空集合或单元素集合
{
int i = 1;
while (i != nums.size())
{
if (nums[i] == nums[i - 1]) // 若元素重复
nums.erase(find(nums.begin(), nums.end(), nums[i])); //则去除重复数字
else // 若元素不重复
i += 1; // 则向后再查看一个元素
}
}
return nums.size(); // 返回结果
}
};
``````

### 3.2.3 其他程序

#### （1）代码

``````#pragma once
#include<vector>    // std::vector
#include<algorithm> // std::unique
using namespace std;

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
nums.erase(std::unique(nums.begin(), nums.end()), nums.end());
return nums.size();
}
};
``````

# 4. 相关知识

## （1） 快慢指针（Fast-Slow Pointer）

https://www.cnblogs.com/hxsyl/p/4395794.html
https://blog.csdn.net/SoftPoeter/article/details/103153564
https://zhuanlan.zhihu.com/p/361049436

## （2） i++与++i的区别

• i++ 即后加加，原理是：先自增，然后返回自增之前的值
• ++i 即前加加，原理是：先自增，然后返回自增之后的值