题目:
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3]
,
Your function should return length = 5
, and A is now [1,1,2,2,3]
.
代码:oj测试通过 Runtime: 120 ms
1 class Solution: 2 # @param A a list of integers 3 # @return an integer 4 def removeDuplicates(self, A): 5 if len(A) < 3 : 6 return len(A) 7 8 pre = 0 9 curr = 1 10 for i in range(2,len(A)): 11 if A[i] == A[curr] and A[i] == A[pre]: 12 continue 13 else: 14 A[curr+1],A[i] = A[i],A[curr+1] 15 pre += 1 16 curr += 1 17 18 return curr+1
思路:
首先长度小于3的可以直接返回,这省去不少事。
主要的逻辑是:从第三个元素开始判断,当前元素i是否与前两个元素相等;如果相等,则i继续往下走;如果不等,则交换curr+1与i位置的元素
刷了几道了Array的题,感觉有一些相似的技巧,就是只遍历一次,不满足条件就交换元素位置。不占用额外的空间。