LeetCode Notes_#26 Remove Duplicates from Sorted Array

LeetCode Notes_#26 Remove Duplicates from Sorted Array

Contents

题目

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

In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure. However a small amount of extra storage space is allowed for auxiliary variables. The input is usually overwritten by the output as the algorithm executes. In-place algorithm updates input sequence only through replacement or swapping of elements. An algorithm which is not in-place is sometimes called not-in-place or out-of-place.
——Wikipedia

Example 1:

Given nums = [1,1,2],

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:

Given nums = [0,0,1,1,1,2,2,3,3,4],

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.

思路及解答

思路

题目的意思是使用in-place的方式去去除顺序数组里的重复元素,也就是说直接修改原来的输入数组,删除重复的元素,然后返回不重复元素的个数

我的思路:
因为是有序的数组,所以如果有重复的,一定是相邻的元素,所以直接从前往后遍历,如果遇到当前数字和后一个数字一样,就把后一个删除,循环直到数组结束,最后返回剩下的数组的长度

解答

nums=[1,1,2,2,4,5]
class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        i=0
        while i<len(nums)-1:
            if nums[i]==nums[i+1]:
                del nums[i+1]
                i=i-1#如果没有这一句,删除之后会出现某一些重复的元素被跳过的情况
            i=i+1
        return len(nums)

64ms,faster than 34%,时间复杂度O(n)

要注意的几点
  1. 不可以用for循环,因为for循环的循环变量是不可以改变的,比如说是range(len(nums)),那么这里的循环范围相当于是一开始就决定好了,之后我删除了数组里边的元素,len(nums)应该是变了,但是循环变量范围不会变,所以就会导致数组越界;用while循环的话,每一次循环前都会去检验一下循环条件,所以不会出现那样的问题
  2. 关于删除元素的方法:参考 删除python数组元素
  3. 一些细节
  • jupyter当中的cell前面如果显示*,说明kernel正忙,其实一般是因为代码写的有问题,出现了类似于死循环或者一些检测不到的异常
  • leetcode上面超时也往往是逻辑错误,如果解法正确,即使最笨的办法一般都是可以通过的,超时了往往要检查有没有逻辑问题

转载于:https://www.cnblogs.com/Howfars/p/9835521.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值