preface
About the LeetCode array type problem related solutions, it can be seen that LeetCode array type problem before doing must see, classification solution summarized the problem, can be used to improve a single. If you think it is helpful, remember to give more likes and attention, thank you!
Topic describes
Given an array nums and a value val, you need to remove all elements equal to val in place and return the new length of the removed array.
Instead of using extra array space, you must only use O(1) extra space and modify the input array in place.
The order of the elements can be changed. You don’t have to worry about elements beyond the new length of the array.
Example 1: Input: nums = [3,2, 3], val = 3 Output: 2, nums = [2,2] Explanation: The function should return the new length 2, and the first two elements in nums are both 2. You don’t have to worry about elements beyond the new length of the array. For example, if the function returns a new length of 2 and nums = [2,2,3,3] or nums = [2,2,0,0], it will also be considered the correct answer.
Example 2: Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3] Explanation: The function should return the new length 5, and the first five elements in nums are 0,1, 3,0,4. Note that these five elements can be in any order. You don’t have to worry about elements beyond the new length of the array.
Link: leetcode-cn.com/problems/re…
Answer key
- The fast pointer is used to iterate over the current array, and the slow pointer is used to extend the result array. When the fast pointer points to a number other than val, it updates both the result array and the slow pointer. Time complexity O(n).
/ * * *@param {number[]} nums
* @param {number} val
* @return {number}* /
var removeElement = function(nums, val) {
const n = nums.length
if (n < 1) return n
let slow = fast = 0
while (fast < n) {
if(nums[fast] ! == val) { nums[slow] = nums[fast] ++slow } ++fast }return slow
};
Copy the code