Given 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 respectively.
It doesn't matter what you leave beyond the returned length.
Given nums = [0,0,1,1,1,1,2,3,3],
Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
It doesn't matter what values are set beyond the returned length.
于是,诞生了如下的思想。首先,用两个指针计算一个数字出现了几次,当然这个题目需要"保证"出现最多两次,所以可以用一个索引就好了,因为快慢指针间隔恒为 2。然后,对于第三个重复元素,直接 remove。需要小心的是,这时候数组长度变短了,如果还按照以前的长度进行遍历,索引会越界,所以干脆维护一个数组即时长度变量并用 while 决定循环好了。
答案
classSolution:defremoveDuplicates(self,nums: List[int]) ->int: idx, l =0,len(nums)while idx < l -2:if nums[idx+2]== nums[idx]: nums.remove(nums[idx+2]) l -=1else: idx +=1returnlen(nums)