【python3】leetcode 27. Remove Element(easy)
阿新 • • 發佈:2018-12-12
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.
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.
注意雖然需要的返回值是int,但是同時會測評你的nums是否去掉了所有val,且是inplace修改,即引用地址沒變
還有一點是val值可能不存在nums中,需要提前判斷
1 我的最優解
思路:因為題目一直提醒說剩下的nums可以不必按順序,所以機智如我,先排序一波,此時val的位置index和數量count是已知的
利用切片把從[index :index+count]的val 都賦值為空[]
class Solution: def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ if not val in nums: return len(nums) num = len(nums) - nums.count(val) nums.sort() nums[nums.index(val):nums.index(val)+nums.count(val)] = [] return num
Runtime: 36 ms, faster than 99.77% of Python3
2 普通思路
計算有幾個val,就刪幾次val
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if not val in nums: return len(nums)
num = len(nums) - nums.count(val)
length = nums.count(val)
for i in range(length):
nums.remove(val)
return num