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