26. Remove Duplicates from Sorted Array
problem
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.
已知一个有序的有重复的数字列表
答案有两个要求,返回无重复的数字个数n,修改列表前n个元素为为无重复元素(不能用额外空间)
solution
- 找到一个不同的元素计数+1
- 找到一个不同元素a,修改列表相应位置元素为a
- 重点是找好比较的中间值
- nums[mid] 有两个作用,一个是作为对比对象,另外一个是修改原数组
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
mid = 0
for i in range(len(nums)):
if nums[mid] != nums[i]:
mid += 1
nums[mid] = nums[i]
return mid+1

浙公网安备 33010602011771号