zoukankan      html  css  js  c++  java
  • LeetCode Easy: 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 by modifying the input array in-place with O(1) extra memory.

    删除给定排好序的字符串中的重复项,并且返回新字符串的长度

    二、解题思路

    注意题中明确说明不要申请额外的空间,开始我就定义了新的变量 list 空集合,编译通过了,但是后来的时候怎么也过不了,如果可以借助新的空间的话,那么此题很简单,比如定义变量 l2 = [ ];然后在给定的 list 中遍历,如果元素在给定的 list 中并且没有在 l2 中就将新元素加到 l2 中,最后返回 l2,长度就是 l2 的长度。上面的思路借助了新的空间。现在只定义两个变量 i 和 j ,其中 i 在给定的整个 list 上移动做遍历,然后判断当前遍历到的 i 位置上的元素,是否与前面的 j 元素相等,如果不等,就作 nums[j+1] = nums[i] 操作,j 也是做 j ++ 操作。

    三、代码

    def removeDuplicates3(nums):
        if len(nums)==0:
            return 0
        j = 0
        for i in range(1,len(nums)):
            if nums[i] != nums[j]:
                nums[j+1] = nums[i]
                j += 1
        return j+1  

    下面还有几种没有被AC的操作,也做一一展示。

    """
     1、最简单的删除重复子串,但是申请了l2额外的空间
    """
    def removeDuplicates1(nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l2 = list(set(nums))
        return l2
    
    """
    遍历,但是申请了l2额外的空间
    """
    def removeDuplicates2(nums):
        l2 = []
        for item in nums:
            if item not in l2:
                l2.append(item)
        return l2
    

     

    参考博客:http://blog.csdn.net/lilong_dream/article/details/19757047   https://www.cnblogs.com/chjbbs/p/5729540.html    https://www.cnblogs.com/chruny/p/4885113.html    http://blog.csdn.net/qq_28119401/article/details/52972467

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    解决android Failed to rename directory 问题
    Android APK反编译
    SQL的bit列名转换成access是/否数据类型,True无效的问题
    android获取屏幕硬件分辨率方法
    cursor:hand 与 cursor:pointer 的区别
    解决android调试是出现:Reinstallation failed due to different application signatures
    Flash as3 基础:AS3中的getChildByName(转)
    机器学习之特征预处理
    用户态和内核态的区别
    深度学习和神经网络的区别(转载)
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8621106.html
Copyright © 2011-2022 走看看