Files
leetcode-master/problems/0026.Remove-Duplicates-from-Sorted-Array.md
youngyangyang04 880ffa83b0 Update
2020-05-18 00:28:44 +08:00

27 lines
895 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 题目地址
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
}
};
```