leetcode26-remove duplicates from sorted array

题目

删除排好顺序的数组里面的重复元素

分析

对于数组nums = [1,1,2],返回 length = 2,并且数组的前两个元素为1,2。也就是说,数组的前length个元素位本数组完全不同的数字。
要求:
不能开辟新的内存空间,空间复杂度O(1)

java代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class  {
public int removeDuplicates(int[] nums) {
if(nums.length == 0){
return 0;
}
int i = 1;
int j = 0;
for(; i<nums.length; i++){
if(nums[i] != nums[j]){
j++;
nums[j] = nums[i];
}
}
return j+1;
}
}

python代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class (object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

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