zoukankan      html  css  js  c++  java
  • LeetCode小白菜笔记[8]:Remove Duplicates from Sorted Array

    LeetCode小白菜笔记[8]:Remove Duplicates from Sorted Array

    26. Remove Duplicates from Sorted Array [Easy]

    题目: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 by modifying the input array in-place with O(1) extra memory.

    Example:

    Given 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.
    

    这个问题即将 list 中不重复的元素按照原有的顺序排起来并返回 list 中不同数值的数量,注意这里要求原位操作,所以必须 O(1) 的空间复杂度。这样我们将每次检测到的与之前不同的值(如 example 中检测到一个2)应当放在之前那个值(即第一个1)所在位置的后一个位置,然后更新要比较的值(更新为2)继续比较,知道遍历完所有元素。emmm。。。这次机制的我吸取教训,先判断是不是特殊情况,如果为空list,直接返回0 。代码如下:

    class Solution(object):
        def removeDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if nums == []:
                return 0
            idx = 0
            for item in nums:
                if not item == nums[idx]:
                    idx = idx + 1
                    nums[idx] = item
            return idx + 1
    

    尽量减少变量名,取 list 元素for循环直接取不要用下标取。结果如下:

    这里写图片描述

    总结:

    时间复杂度线性,空间复杂度常数。这个题比较简单,没啥好总结的。

    THE END

    2017/12/16 Sat 16:26

  • 相关阅读:
    svn 更新
    首尾渐变
    sublime常用快捷键
    【CSS3】transition过渡和animation动画
    JS实现奇偶数的判断
    style、currentStyle、getComputedStyle区别介绍
    JavaScript中判断对象类型的种种方法
    CSS3 animation动画,循环间的延时执行时间
    EMCA创建em资料库时报错
    OS Kernel Parameter.semopm
  • 原文地址:https://www.cnblogs.com/morikokyuro/p/13256848.html
Copyright © 2011-2022 走看看