您的位置:首页 > 编程语言 > Python开发

【LEETCODE】80-Remove Duplicates from Sorted Array II [Python]

2016-01-21 20:00 615 查看
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of
nums being 1, 1,
2, 2 and
3. It doesn't matter what you leave beyond the new length.

题意:
接Remove Duplicates
如果允许重复的数字最多出现两次呢?
例:
给一个数组:nums = [1,1,1,2,2,3]
返回length = 5, 即 1, 1, 2, 2 and 3

思路:
两个指针 pre , cur
A[cur] 如果和 A[pre]及 A[pre-1]的值想等,则 cur进1,一直到 A[cur] 不再等于 A[pre]及 A[pre-1]
当不是上述情况时,pre进1, A[pre]换成 A[cur] ,cur进1,也就是把多余两个的数字,用后面的非重复数字替换掉



Python:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

n=len(nums)
if n<=2:
return n

pre=1
cur=2

while cur<n:

if nums[cur]==nums[pre] and nums[cur]==nums[pre-1]:
cur+=1
else:
pre+=1
nums[pre]=nums[cur]
cur+=1
return pre+1


错误分析:







第二个图,如果遇到多余3个相等的数字的时候,就会给出错误答案
第一个图,用一个 while 把第二个图的错误改过来了,但是结果数组的顺序又被搞乱了,虽然要求是返回 length,但是内部会检测是否保证原有大小顺序
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: