Nuggets team number online, help you Offer rimmon! Click to see details

I. Topic Description:

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.

  • The sample

 

Explanation: Why is the return value an integer, but the output answer is an array? Note that the input array is passed as a "reference," which means that changes to the input array in the function are visible to the caller. You can imagine the internal operation as follows: // nums is passed by reference. Int len = removeElement(nums, val); // Modifying the input array in the function is visible to the caller. // Depending on the length your function returns, it prints out all the elements in the array within that length range. for (int i = 0; i < len; i++) { print(nums[i]); } 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. 0 <= nums.length <= 100 0 <= nums[I] <= 50 0 <= val <= 100Copy the code

 

Ii. Thinking analysis:

  • Do you notice any striking similarities between this problem and the last one?
  • Look for the same value as the given element, delete it, note that the index should be subtracted

Three, AC code

/** * @param {number[]} nums * @param {number} val * @return {number} */ var removeElement = function(nums, val) { for (let i = 0; i < nums.length; i++) { if(nums[i] === val){ nums.splice(i,1); i--; } } return nums.length; }; Status: Elapsed time: 88 ms Memory consumption: 38.1 MBCopy the code

Four,

  • Of course there’s more than one way to do it, and there are many ways to do it;
/** * @param {number[]} nums * @param {number} val * @return {number} */ var removeElement = function(nums, val) { if (nums.length == 0) return 0; let i = 0; for (let j = 0; j < nums.length; j++) { if (nums[j] ! = val) { nums[i] = nums[j]; i++; } } return i; };Copy the code
  • So let’s do the same thing we did last time
Execution time: 76 ms Memory: 37.8 MBCopy the code

For reference only

Refer to the topic

  • Force button (LeetCode)