🐣

# [英語解説] LeetCode 27: Remove Element in-Place

2023/05/14に公開

Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` in-place. The order of the elements may be changed. Then return the number of elements in `nums` which are not equal to `val`.

Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things:

Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`.
Return `k`.

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,,]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are >underscores).

Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,,,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are >underscores).

## Brute Force Method

Time Complexity O(N^2)

``````class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = len(nums)
i = 0
while i <= len(nums) - 1:
if nums[i] == val and i < k:
for j in range(i+1, len(nums)):
nums[j-1], nums[j] = nums[j], nums[j-1]
k -= 1
i -= 1
i += 1
return k
``````

## Double Pointers (Fast and slow pointer)

The Two-Pointers Method, also referred to as the Fast-Slow Pointer Method, is an approach that enables the simultaneous execution of two loops within a single loop.

Here's the definition of each pointer:

Fast Pointer traverse the oringal array searching elements in the new array (which contains no element eqauls to val).

Slow Pointer indicates the position where the index of the new array is updated. It is the right boundary of the new target array.

``````class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
slow = 0
for fast in range(len(nums)):
if nums[fast] != val:
nums[fast], nums[slow] = nums[slow], nums[fast]
slow += 1

return slow
``````

## Double Pointers (Left & Right pointer)

we divide the array into two segments:

The first segment is the valid part, which stores elements that are not equal to "val."
The second segment is the invalid part, which stores elements that are equal to "val."

``````class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
if nums[left] == val:
nums[left], nums[right] = nums[right], nums[left]
left -= 1
right -= 1
left += 1
return left
``````