题意: 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 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.
思路:这题和26. Remove Duplicates from Sorted Array 思路是差不多的,但是我一开始思路就错了,想着用两个指针和一个num来求两个相异数之间的差,然后通过各种if来求结果,但是。。。。。。一直都没写出来。。。。情况太多了。。。。后来看了一下discussion,发现自己太naive了。。。。其实用一个指针就好了,而且对于这类题都能解:
def removeDuplicates(self, nums):
i = 0
for n in nums:
if i < 2 or n > nums[i-2]:
nums[i] = n
i += 1
return i
里面的2换成至多出现的次数就好了,其实这题很关键的信息我之前一直都忽略了。。这是一个排序好的数组,所以大小关系比不等关系重要多了!