Topic link
https://leetcode-cn.com/problems/remove-element/submissions/
Topic describes
Given an array nums and a value target, you remove all elements equal to target in place, returning the new length of the removed array.
Instead of using extra array space, you must modify the input array in place and do so with O(1) extra space.
The order of elements can be changed. You don’t need to worry about the element after the new length in the array.
Example 1:
Given nums = [3.2.2.3], val = 3.
The function should return a new length of 2, and the first two elements in nums are both 2.
Copy the code
You don't need to worry about the element after the new length in the array.
Example 2:
Given nums = [0.1.2.2.3.0.4.2], val = 2.
The function should return a new length of 5, and the first five elements in nums are 0, 1, 3, 0, 4.
Notice that these five elements can be in any order.
Copy the code
You don't need to worry about the element after the new length in the array.
Description:
Why is the return value an integer, but the output answer is an array?
Note that the input array is passed “by reference,” which means that modifying the input array in a function is visible to the caller.
You can imagine the internal operation as follows:
// Nums is passed by reference. That is, no copies of the arguments are made int len = removeElement(nums, val); Copy the code
// Modifying the input array in a function is visible to the caller. // Depending on the length returned by your function, it prints out all elements in the array within that length. for (int i = 0; i < len; i++) { print(nums[i]); }
Boundary conditions:
An empty array returns 0.
Double pointer method
We use fast and slow Pointers that initially point to the same element, move the fast pointer forward, and assign the value to the element that the slow pointer points to when we encounter an element that is not equal to target.
class Solution {
func removeElement(_ nums: inout [Int], _ target: Int) -> Int {
guard! nums.isEmptyelse { return 0 }
var i = 0
for j in 0..<nums.count {
ifnums[j] ! = target { nums[i] = nums[j] i +=1}}return i
}
}
Copy the code
- Time complexity: O(n)
- Space complexity: O(1)