27. Remove Element
給定一個(gè)數(shù)組nums和一個(gè)val值,在nums中就地移除該val的所有并返回新的長(zhǎng)度。 不要為其他數(shù)組分配額外空間,必須通過(guò)在O(1)額外內(nèi)存中就地修改輸入數(shù)組來(lái)實(shí)現(xiàn)此目的。
元素的順序可以改變。
在nums新的長(zhǎng)度以后留下的數(shù)字并沒(méi)有關(guān)系。 比如長(zhǎng)度為2,則nums[2]及以后的并不重要
JAVA 15ms
class Solution {
public int removeElement(int[] nums, int val) {
int count = 0;
for(int i = 0 ; i< nums.length; i++){
if(val != nums[i]){
nums[count++] = nums[i];
}
}
return count;
}
}
Python 38ms
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
count = 0
for i in range(len(nums)):
if (val != nums[i]):
nums[count] = nums[i]
count += 1
return count
另一種python更快解法,直接利用list 的del特性
注:list del是根據(jù)索引位置來(lái)刪除元素
比如
a = [3,2,2,1]
del a[1,3]
print a
結(jié)果[3]
a[::-1]用法:翻轉(zhuǎn)list
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
for i in range(len(nums))[::-1]: # a[::-1]翻轉(zhuǎn),即i為倒序
if nums[i] == val:
del nums[i]