有序数组去重2--Remove Duplicates from Sorted Array II

https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

Remove Duplicates from Sorted Array II

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 1122 and 3. It doesn't matter what you leave beyond the new length.

题意:有序数组,去重,允许至多有2个重复项

解题思路:一种巧妙的解法。使用两个指针prev和curr,判断A[curr]是否和A[prev]、A[prev-1]相等,如果相等说明curr指针指向的是第3个重复数,继续向后遍历,直到不相等时,将curr指针指向的值赋值给A[prev+1],最后prev+1值就是数组的长度。pre指针控制最终的数组形式。

 1 class Solution:
 2     # @param {integer[]} nums
 3     # @return {integer}
 4     def removeDuplicates(self, nums):
 5         A=nums
 6         if len(A)<=2: return len(A)                     #因允许最多2个重复,则<=2时不用去重
 7         prev=1;curr=2                                   #用pre来控制最终的数组,curr来遍历数组进行判断
 8         while curr<=len(A)-1:
 9             if A[curr]==A[prev] and A[curr]==A[prev-1]: #若curr指向第3个重复数,则pre控制在第2个重复处,curr继续遍历
10                 curr+=1
11             else:                                       #若没有重复或重复在2内,将当前curr数加到pre后,pre向后移动继续控制住
12                 prev+=1
13                 A[prev]=A[curr]
14                 curr+=1
15         return prev+1                                    #返回最终数组的pre+1即长度

 

转载于:https://www.cnblogs.com/lzsjy421/p/4621859.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值