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)                           # 返回长度
  • 相关阅读:
    在二进制与文本之间转换plist文件
    iOS 音频分贝的计算
    iOS 圆形水波浪效果实现
    iOS画圆、画线
    iOS IM开发准备工作(四)CocoaAsyncSocket的使用
    iOS IM开发准备工作(三)乱说Socket
    iOS IM开发准备工作(二)protobuf-objc安装及使用
    iOS IM开发准备工作(一)XML解析
    iOS IM开发blog写作计划
    西游记倒着看。。我从贴吧看来的
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10796846.html
Copyright © 2011-2022 走看看