Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Today again a simple question, brush up his ~

27. Remove elements [Easy]

Leetcode-cn.com/problems/re…

Given an array of nums and a value of val, you remove all elements equal to val in place and return the new length of the 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 elements can be changed. You don’t need to worry about the element after the new length in the array.

Fast or slow pointer

Like removing duplicates from an ordered array, fast I is used to iterate over nums, and slow j is used to maintain an array.

  • [Note] The internal execution order of the statement in this problem is different from that in question 26. Assign value first and then increment
  • [Note] Because of the increment after, the final return value does not need to be manually+ 1
/ * * *@param {number[]} nums
 * @param {number} val
 * @return {number}* /
var removeElement = function(nums, val) {
    let j = 0;
    for(let i = 0; i< nums.length; i++){
        if(nums[i] !== val){
            nums[j] = nums[i];
            j++;
        }
    }
    return j;
};
Copy the code

[solution 2] Colliding Pointers

Since there is no requirement on the order of the elements, you can replace the element with the last one when you encounter an element that needs to be discarded (the element equal to val)

Define two colliding Pointers left and right

var removeElement = function(nums, val) {
  let left = 0;
  let right = nums.length - 1;
  while (left <= right) {
    if (nums[left] === val) {
      nums[left] = nums[right];
      right--;
    } else{ left++; }}return left;
};
Copy the code