Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

Mobile zero

The original address

Given an array nums, write a function to move all zeros to the end of the array while preserving the relative order of the non-zero elements.

Note that you must operate on the array in place without copying it.

Example 1:

Enter: nums = [0.1.0.3.12] output: [1.3.12.0.0]
Copy the code

Example 2:

Enter: nums = [0] output: [0]
Copy the code

Thought analysis

Methods a

  1. The first reaction is to filter out the non-zero elements of the array, and then add zeros according to the length of the array.
  2. Just do it. Use arraysfilterMethod, filter out the non-zero array elements, and getarrNo;
  3. The loop array is going to be less thanarrNoElements of the length subscript are assigned to correspondarrNoAll the rest are 0’s.

Method 2

  1. Extend the use of arrayssortMethods;
  2. We all know about arrayssortMethod can sort an array by a method;
  3. So you can sort the array by b, if B is 0, return -1, a is in front of B, b is behind A, and you put the 0 at the end of the array.

AC code

Methods a

/ * * *@param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    const arrNo = nums.filter(item= > item)
    for(let i = 0; i < nums.length; i++) {
        if(i < arrNo.length) {
            nums[i] = arrNo[i]
        } else {
            nums[i] = 0}}};Copy the code

Results:

  • Result: Yes
  • Execution time: 88 ms, beating 71.67% of users in all JavaScript commits
  • Memory consumption: 46 MB, beating 11.80% of all JavaScript commits
  • Pass test case: 74/74

Method 2

/ * * *@param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    nums.sort((a, b) = > b ? 0 : -1)};Copy the code

Results:

  • Result: Yes
  • Execution time: 80 ms, beating 90.48% of users in all JavaScript commits
  • Memory consumption: 45.2 MB, beating 56.61% of all JavaScript commits
  • Pass test case: 74/74

END