zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    什么是DMI,SMBIOS,符合SMBIOS规范的计算机的系统信息获取方法
    Android init.rc执行顺序
    JVM-类的四种载入方式
    Intellij-创建Maven项目速度慢
    Intellij-工程目录下隐藏不想显示的文件和文件夹
    JVM-类加载机制(Java类的生命周期)
    Git-远程仓库的使用
    JavaSE-反射-获取类或者对象的四种方法
    工厂模式(Factory Pattern)
    Redis-配置认证密码
  • 原文地址:https://www.cnblogs.com/zhuifengjingling/p/5243420.html
Copyright © 2011-2022 走看看