LeetCode80: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.

LeetCode:链接

第一种方法:使用两个指针prev和curr,判断A[curr]是否和A[prev]、A[prev-1]相等,如果相等curr指针继续向后遍历,直到不相等时,将curr指针指向的值赋值给A[prev+1],这样多余的数就都被交换到后面去了。最后prev+1值就是数组的长度。

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) <= 2:
            return len(nums)
        pre = 1
        cur = 2
        while cur < len(nums):
            if nums[cur] == nums[pre] and nums[pre] == nums[pre-1]:
                cur += 1
            else:
                pre += 1
                nums[pre] = nums[cur]
                cur += 1
        return pre + 1

第二种方法:在每一次插入过程中,其实只要把要插入的元素和倒数第二个元素进行比较,如果相同,就忽略,因为倒数第一个数是夹在它们中间的,如果它们相等,那么就会有三个数相等;如果不同,就可以插入,因为在这样的情况下,最多只有倒数第二、倒数第一两个数相等。

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 0
        for i in range(len(nums)):
            if count < 2 or nums[count - 2] != nums[i]:
                nums[count] = nums[i]
                count += 1
        return count

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84591959
今日推荐