# LeetCode 26. 删除排序数组中的重复项

### 中文版：

// nums 是以“引用”方式传递的。也就是说，不对实参做任何拷贝
int len = removeDuplicates(nums);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i < len; i++) {
print(nums[i]);
}

### 英文版：

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

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

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.
Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.
Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}

1、Java：

class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0 || nums == null){
return 0;
}

int size = 0;
for(int i = 0; i < nums.length; i++){

if(nums[size] != nums[i]){
nums[++size] = nums[i];
}
}
return size + 1;
}
}

2、Python：

class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = 0
if len(nums) == 0:
return length

for i in range(len(nums)):
if nums[length] != nums[i]:
length += 1
nums[length] = nums[i]

# nums[++length] = nums[i] 这是Java用法，Python中没有 ++length 用法

return length + 1

### 解题报告：

1、本题主要算法为同向双指针，也叫快慢指针。

2、在for 循环中， i 是快指针，length 或 size 是慢指针。

3、再次做题，卡住的点是 nums[++size] = nums[i]; 这是代码中最关键的一句。判断快慢指针所指向的值是否一致，如果不一致则复制，并把慢指针后移一位；如果一致则快指针继续走。

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客