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  好运会来吗?

  • 相关阅读:
    Java数组(1):数组与多维数组
    Java内部类(5):应用例
    Java内部类(4):静态内部类&接口内部类
    Java内部类(3):局部内部类
    Java内部类(2):普通的成员内部类
    Java内部类(1):概述
    Java中验证编码格式的一种方法
    Mybatis高级结果映射
    Mybatis Guide
    Java泛型(11):潜在类型机制
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14623563.html
Copyright © 2011-2022 走看看