【LeetCode每天一题】Remove Duplicates from Sorted Array II(移除有序数组中重复的两次以上的数字)

时间:2023-03-09 07:13:38
【LeetCode每天一题】Remove Duplicates from Sorted Array II(移除有序数组中重复的两次以上的数字)

  Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

 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.

Example 2:

 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.

思路

     这道题主要是需要将排序数组中重复唱过两次以上的数组除去并返回最后的长度, 因此对于此我们可以从头开始遍历,如果后面的元素和当前元素相等,我们使用一个循环来将后面相等的元素直接去除。不相等则遍历下一个元素,最后返回数组的长度。时间复杂度为O(n),空间复杂度为O(1)。
解决代码


 class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
i, nums_len = 0, len(nums) # 开始下标和数组长度
while i < nums_len:
if i < nums_len-1 and nums[i] == nums[i+1]: # i的长度小于nums_len-1的长度,否则nums[i+1]会越界。
i, tem = i+2, nums[i] # 直接将下标i指向 第三个元素
while i < nums_len and tem == nums[i]: # 将后面与tem相同的元素删除
nums.pop(i)
nums_len -= 1 # 因此使用的是pop(),所以每次pop之后数组的长度会减1,但是i的下标可以不表
continue
i += 1
return len(nums) # 返回长度