您的位置:首页 > 其它

leetcode Remove Element

2015-12-02 23:21 369 查看
https://leetcode.com/problems/remove-element/

题意有点模糊

class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if len(nums) == 0:
return 0
j = len(nums) - 1 #j仅仅表示回收

for i in range(len(nums) - 1, -1, -1):
if nums[i] == val:
nums[i], nums[j] = nums[j], nums[i]
j -= 1

return j+1


自己重写code, 有bug。要向上面一样,i从后往前扫,j+1为结果。跟move zero一样,要从后面那么i,j就都从后面,否则就都从前面

class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if len(nums) == 1 and nums[0] == val: return 0
if len(nums) == 1 and nums[0] != val: return 1
i,j = 0, len(nums) - 1

while j >= 0 and nums[j] == val:
j -= 1
if j == -1:
return 0

while i < j:
if nums[i] == val and nums[i] != nums[j]:
nums[i],nums[j] = nums[j], nums[i]
j -= 1
i += 1

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