27. Remove Element@python
Given an array nums and a value val, 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.
题目地址: Remove Element
难度: Easy
题意: 删除指定值,并将其他元素移动前面
思路:
遍历,双指针
代码:
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ n = len(nums) i, j = 0, n-1 while i <= j: if nums[i] == val: nums[i], nums[j] = nums[j], nums[i] j -= 1 else: i += 1 return i
时间复杂度: O(n)
空间复杂度: O(1)

浙公网安备 33010602011771号