27. Remove Element

别说谁变了你拦得住时间么 提交于 2020-07-24 13:05:31

27. Remove Element

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.

Example 1:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length=5, with the first five elements of nums containing 0, 1, 3, 0 and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

Summary

This is a pretty easy problem, but one may get confused by the term "in-place" and think it is impossible to remove an element from the array without making a copy of the array.

Hints

  1. Try two pointers.
  2. Did you use the fact that the order of elements can be changed?
  3. What happens when the elements to remove are rare?

Solution


Approach 1: Two Pointers

Intuition

Since this question is asking us to remove all elements of the given value in-place, we have to handle it with O(1)O(1) extra space. How to solve it? We can keep two pointers ii and j, where ii is the slow-runner while j is the fast-runner.

Algorithm

When nums[j] equals to the given value, skip this element by incrementing j. As long as nums[j] != val we copy nums[j] to nums[i] and increment both indexes at the same time. Repeat the process until j reaches the end of the array and the new length is i.

This solution is very similar to the solution to Remove Duplicates from Sorted Array.

class Solution:
    def removeElement(self, nums, val):
        n = len(nums)
        i = 0
        for j in range(n):
            if nums[j] != val:
                nums[i] = nums[j]
                i += 1
        return i

Complexity analysis

  • Time complexity: O(n). Assume the array has a total of n elements, both i and j traverse at most 2n steps.

  • Space complexity: O(1).

Approach 2: Two Pointers - when elements to remove are rare

Intuition

Now consider cases where the array contains few elements to remove. For example, nums = [1,2,3,5,4], val = 4. The previous algorithm will do unnecessary copy operation of the first four elements. Another example is nums = [4,1,2,3,5], val = 4. It seems unnecessary to move elements [1,2,3,5] one step left as the problem description mentions that the order of elements could be changed.

Algorithm

When we encounter nums[i]=val, we can swap the current element out with the last element and dispose of the last one. This essentially reduces the array's size by 1.

Note that the last element that was swapped in could be the value you want to remove itself. But don't worry, in the next iteration, we will still check this element.

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

Complexity analysis

  • Time complexity: O(n). Both i and n traverse at most n steps. In this approach, the number of assignment operations is equal to the number of elements to remove. So it is more efficient if elements to remove are rare.

  • Space complexity: O(1).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!