有序数组去重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即长度

 

posted @ 2015-07-05 11:06  小榛子  阅读(105)  评论(0编辑  收藏  举报