Remove Duplicates from Sorted Array II @ LeetCode (Python)
kitt
posted @ 2014年3月22日 13:23
in LeetCode
, 3655 阅读
使用一个快指针fast来遍历数组, 一个慢指针slow来记录最终结果, 用count记录同一个数出现的次数, 如果遇到新数或count<=2则更新A[slow]。
Use a "fast" pointer to traverse the array, a "slow" pointer to record final results. Use "count" to record the occurrences of a number. If "fast" meets a new number or count <= 2, then update A[slow].
class Solution:
# @param A a list of integers
# @return an integer
def removeDuplicates(self, A):
lenA = len(A)
if lenA == 0: return 0
slow = 0
count = 1
for fast in xrange(1, lenA):
if A[fast] == A[fast - 1]:
count += 1
if count <= 2:
slow += 1
A[slow] = A[fast]
else:
count = 1
slow += 1
A[slow] = A[fast]
return slow + 1
评论 (0)