public class Solution {
public int RemoveDuplicates(int[] nums) {
var len = nums.Length;
if (len == )
{
return ;
}
else
{
var pre = nums[];
var diffindex = ;
for (int i = ; i < nums.Length; i++)
{
if (pre != nums[i])
{
nums[++diffindex] = nums[i];
pre = nums[i];
}
}
return diffindex + ;
}
}
}

python实现如下:

 class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
s = set()
n = len(nums)
count =
i,j = ,
while i < n:
if len(s) == or nums[i] not in s:
s.add(nums[i])
nums[j] = nums[i]
i +=
j +=
count +=
else:
i +=
return count

不实用额外的空间,实现如下:

 class Solution:
def removeDuplicates(self, nums: 'List[int]') -> int:
n = len(nums)
i =
j = i +
count =
while i < n:
while j < n and nums[i] == nums[j]:
j +=
count +=
if i + < n and j < n:
nums[i+] = nums[j]
i +=
else:
return count
return count
05-18 11:01