26. Remove Duplicates from Sorted Array

题目

Given a sorted array, 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 in place with constant memory.

For example,
Given input array 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 new length.

题意

对列表操作,去除重复的列表,不开辟新的数组

Python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2: return len(nums)
k=1
pre=nums[0]
for ni in nums[1:]:
if ni!=pre:
nums[k]=ni
k+=1
pre=ni
return k
如果觉得有帮助,给我打赏吧!