用python刷LeetCode DAY 3
题目:移除元素
题目要求如下:
若使用python内置的函数和方法可以很快求解:
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中元素为val的个数
nums.remove(val) # remove一次只能移除一个最靠前的元素,所以有多少个val就要删除多少次
return len(nums)
如果想要自己实现不依赖python内置函数,则需要用到双指针:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
fast = 0 # 定义快慢两个指针
slow = 0
while fast < len(nums):
if nums[fast] != val:
nums[slow] = nums[fast]
slow = slow + 1
fast = fast + 1
return slow
值得注意的是,在LeetCode上提交代码后,用双指针法通过时长要比第一种方法所用时长更久,但双指针仍然是一种值得掌握的思想,在数组,链表,字符串等面试题中都用经常用到
方法所用时长更久,但双指针仍然是一种值得掌握的思想,在数组,链表,字符串等面试题中都用经常用到