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

来源:互联网 发布:c语言程序代码大全 编辑:程序博客网 时间:2024/06/06 15:34

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 ofnums being 1, 1,2, 2 and3. It doesn't matter what you leave beyond the new length.


题意:

接Remove Duplicates

如果允许重复的数字最多出现两次呢?

例:

给一个数组:nums = [1,1,1,2,2,3]

返回length = 5, 即 1122 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,但是内部会检测是否保证原有大小顺序




0 0
原创粉丝点击