您的位置:首页 > 编程语言 > Python开发

[Leetcode][python]Remove Element

2017-08-27 12:41 253 查看

题目大意

去掉数组中等于elem的元素,返回新的数组长度,数组中的元素不必保持原来的顺序。

解题思路

双指针

使用头尾指针,头指针碰到elem时,与尾指针指向的元素交换,将elem都换到数组的末尾去。

代码

判断与指定目标相同

class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
front = len(nums)-1
behind = len(nums)-1
number = 0
while front >= 0:
print 'now:', front, behind
if nums[front] == val:
print front, behind
number += 1
nums[front], nums[behind] = nums[behind], nums[front]
behind -= 1
front -= 1
print number
return len(nums) - number


判断与指定目标不同

class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""

size = 0
length = len(nums)

for i in range(length):
if nums[i] != val:

nums[size] = nums[i]
size += 1
return size


总结

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode