今天做的这道题目是删除列表中的重复元素,是同之前的有序列表的题目不太一样,但是思路差不多,因此先看下题目:
Given an array nums and a value val, remove all instances of that value in-place 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.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
给出一个数组nums和数值val,删除所有等于val值的元素
Example 1:
Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,Your function should return length = 5, with the first five elements of 0,1,3,0,4
这两个例子很容易理解,就不用多说
说下我自己的思路吧:
首先,我设置一个循环,然后发现val在目标数组nums中的时候,我就删除这个元素,外层循环用while而不是用for的原因是,如果用for循环遍历,会出现少删的情况,比如遍历了一个元素,然后删除它了之后,会跳过这个下标继续往前走,举个例子:
假如nums = [1,2,2,2,3],val=25
使用for循环来遍历删除,当遇到第一个2的时候删除掉2,但是此时i已经遍历到第一个2的下标了,也就是i指向的是第二个元素,接下来删除掉2之后呢,数组更新了成为[1,2,2,3],但是此时i依旧继续遍历,会指向下一个元素,也就是i会指向数组中第三个元素,因此它会删除处于第三个元素的2,此时第二个位置上的2,也就是第一次更新后的数组nums的第二个元素2,不会被删除,这也就是什么不使用for循环来做。
下面是我的代码:
# -*-Coding:UTF-8-*- # Author:Tian YUan # Date:2019/4/1 Happy April Fool's Day! class Solution: def removeElement(self, nums: list, val: int) -> int: while val in nums: nums.remove(val) # print(nums) return len(nums) if __name__ == '__main__': print(Solution().removeElement([3,2,2,31,2,3,5,5,6],2))
代码很好看懂,下面是我的结果以及在leetcode上提交的结果:
谢谢!