zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】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.

    思路

         这道题主要是需要将排序数组中重复唱过两次以上的数组除去并返回最后的长度, 因此对于此我们可以从头开始遍历,如果后面的元素和当前元素相等,我们使用一个循环来将后面相等的元素直接去除。不相等则遍历下一个元素,最后返回数组的长度。时间复杂度为O(n),空间复杂度为O(1)。
    解决代码

    
    
     1 class Solution(object):
     2     def removeDuplicates(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: int
     6         """
     7         if not nums:
     8             return 0
     9         i, nums_len = 0, len(nums)   # 开始下标和数组长度
    10         while i < nums_len:           
    11             if i < nums_len-1 and nums[i] == nums[i+1]:    #  i的长度小于nums_len-1的长度,否则nums[i+1]会越界。
    12                 i, tem = i+2, nums[i]                       # 直接将下标i指向 第三个元素
    13                 while i < nums_len and tem == nums[i]:    # 将后面与tem相同的元素删除
    14                     nums.pop(i)
    15                     nums_len -= 1                         # 因此使用的是pop(),所以每次pop之后数组的长度会减1,但是i的下标可以不表   
    16                 continue
    17             i += 1
    18         return len(nums)                           # 返回长度
  • 相关阅读:
    Java(14):面向对象、封装、继承、方法重写、多态、抽象类与接口、内部类
    Java(13):数组、Arrays类、冒泡排序
    Java(12):方法、重载、命令行传参、可变参数、方法调用
    Java(11):switch、dowhile、九九乘法表、打印质数、打印三角形
    Java(10):用户交互Scanner
    Java(9):包
    Java(8):运算符
    Java(7):变量和常量及其规范、作用域
    Mybatis 打印日志
    mysql 更新数据
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10796846.html
Copyright © 2011-2022 走看看