LeetCode Easy: 27. Remove Element
一、题目
Given an array and a value, 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.
不借助新的空间,删除给定数组中的与给定的 val 相同的元素,返回新数组的长度,新数组的末尾是什么不关心。
二、思路
首先不考虑鲁棒性,定义两个指针,其中一个指针遍历整个数组,另外一个指针负责计数即当前数组元素不等于给定 val 时做加 1操作 ,同时将该元素前移。大的考虑就这些。
三、代码
#coding:utf-8
def removeElement(nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
numslenth = len(nums)
j=0
# if numslenth == 0:
# return 0
# if numslenth == 1 and val == nums[0] :
# return 0
# if numslenth == 1 and val != nums[0] :
# return 1
for i in range(0,numslenth):
if nums[i] != val:
nums[j] = nums[i]
j += 1
print(j,"\n",nums)
return j
if __name__ == '__main__':
nums = [5]
val = 3
removeElement(nums,val)
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
浙公网安备 33010602011771号