LeetCode9——移除元素
前言:
题目内容:
示例 1:
示例 2:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-element
python实现:
方法一:
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 nums[i] != val:
nums[count ] = nums[i]
print(nums)
count += 1
return count
if __name__ == '__main__':
nums = [1, 1, 2,2,2,3,2,2]
val=2
a = Solution()
print(a.removeElement(nums,val))
方法二:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
for i in range(nums.count(val)):
nums.remove(val)
return len(nums)
if __name__ == '__main__':
nums = [1, 1, 2,2,2,3,2,2]
val=2
a = Solution()
print(a.removeElement(nums,val))