26. Remove Duplicates from Sorted Array

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了26. Remove Duplicates from Sorted Array相关的知识,希望对你有一定的参考价值。

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn‘t matter what you leave beyond the new length.

AC代码:

class Solution(object):
    def removeDuplicates(self, nums):
        i, pre = 0, None
        while i < len(nums):
            if nums[i] != pre:
                pre = nums[i]
                i += 1
            else:
                del nums[i]
        return len(nums)

思路:

循环删除重复的元素,最后的列表就为所求列表。

注意不能用remove删除,因为remove是按值删除,而原列表会有重复值。

也不能用for循环,因为涉及了删除元素,游标不可控的情况下删除元素会导致直接跳过下一个元素。

 

这种方法没有问题,但是我们注意到原题要求中有这么一句: It doesn‘t matter what you leave beyond the new length.

意思是只需要最后所求列表长度的前面元素是正确的就可以,对于超过长度的元素,可以不用删除。

这就告诉我们可以用另外一种思路,即重新赋值一遍列表前面不重复的元素,剩下的就不用操作。

这种方法需要两个游标:

class Solution(object):
    def removeDuplicates(self, nums):
        n = len(nums)
        if n < 2: return n
        current = 1
        for i in xrange(1, n):
            if nums[i] != nums[i - 1]:
                nums[current] = nums[i]
                current += 1
        return current

本题需要仔细审题,题目不难。

以上是关于26. Remove Duplicates from Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

26. Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array

#26 Remove Duplicates from Sorted Array

LeetCode OJ 26. Remove Duplicates from Sorted Array

leetcode 26. Remove Duplicates from Sorted Array 80. Remove Duplicates from Sorted Array II

26. Remove Duplicates from Sorted Arrayeasy