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

  • 相关阅读:
    mongodb简介
    tomcat简介
    date的详细说明
    30岁前成功的12条黄金法则
    2012春晚经典语录
    统计文件中某个单词出现的次数
    nginx简介
    ATM取款机系统模拟仿真
    十三种时间管理方法
    笔试常见的智力题 附答案
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14623563.html
Copyright © 2011-2022 走看看