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.
给定一个排好序的列表,把重复的数字去掉使得每个元素只出现一次并且返回新的长度(此处指不重复元素一共多少个)。
不允许给分配额外的空间给一个新的列表。
举例:
给定列表:[1,1,2]
你的函数应该返回2,并且列表开头两个元素应该是1,2。
解法:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
else:
flag = 0
for i in range(1,len(nums)):
if nums[flag] != nums[i]:
flag += 1
nums[flag] = nums[i]
return flag + 1
思路:
从列表第一个元素开始,定义一个标识为flag,一开始的值为列表第一个元素的值,从第二个元素开始循环,如果下一个元素不等于flag,计数(flag)加1,并且把下一个元素的值给flag位置所在的值。最后返回计数加1。