LeetCode Remove Element
Remove Element for solving LeetCode Problems
Original question
Deletes an element of a specific value in an array and returns the length of the deleted array.
Note:
The order of numbers after the operation ends does not need to be processed for the part that exceeds the returned length.
Example:
Input: nums [1, 2, 3, 4, 3, 2, 1], val = 1
Output: 5
Solutions
The left and right pointers move closer to the middle. The left pointer finds a value equal to val, the right pointer finds the first value not equal to val, and assigns the value pointed to by the right pointer to the left pointer. Continue to move closer to the center.
AC Source Code
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ left = 0 right = len(nums) - 1 while left <= right: while left <= right and nums[left] != val: left += 1 while left <= right and nums[right] == val: right -= 1 if left < right: nums[left] = nums[right] left += 1 right -= 1 return right + 1if __name__ == "__main__": assert Solution().removeElement([1, 2, 3, 4, 3, 2, 1], 1) == 5 assert Solution().removeElement([2], 3) == 1