zoukankan      html  css  js  c++  java
  • Leetcode 26. Remove Duplicates from Sorted Array

    Description: Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns 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.

    Link: 26. Remove Duplicates from Sorted Array

    Examples:

    Example 1:
    Input: nums = [1,1,2]
    Output: 2, nums = [1,2]
    Explanation: 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 returned length. Example 2: Input: nums = [0,0,1,1,1,2,2,3,3,4] Output: 5, nums = [0,1,2,3,4] Explanation: Your function should return length = 5, with the first five elements of nums being modified to
    0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.

    思路: 删除有序数组中的重复元素,返回长度。记录前一个元素的值,如何当前与之相同,就删除当前元素,否则更新前一个元素和长度。

    class Solution(object):
        def removeDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if len(nums) <= 1: return len(nums)
            i, pre = 1, nums[0]
            while nums[i:]:
                if nums[i] == pre:
                    nums.pop(i)
                else:
                    pre = nums[i]
                    i += 1
            return i

    但似乎不需要物理删除,只要内部调整位置就可。两个指针,left指向要替换的位置,right指向要替换的数。

    class Solution(object):
        def removeDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            n = len(nums)
            if n <= 1: return n
            left, right = 0, 1
            while right < n:
                while right < n and nums[left] == nums[right]:
                    right += 1
                left += 1
                if right < n:
                    nums[left] = nums[right]
            return left

    日期: 2021-04-06  好运会来吗?

  • 相关阅读:
    013.[转] 云原生
    012.[转] 云计算
    011.maven 继承与聚合
    Window常用且通用快捷键
    Hibernate Validator Engine的用法
    Mybatis书写
    Ajax错误
    apache commons lang架包介绍
    Mybatis使用Mybatis-generator插件及配置(数据库逆向工程)
    二分搜索树
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14623563.html
Copyright © 2011-2022 走看看