[Leetcode] [JavaScript] Move Zeroes

Source: Internet
Author: User

Move Zeroes

Given an array nums , write a function to move all's to the 0 end of it while maintaining the relative order of the No N-zero elements.

For example, given nums = [0, 1, 0, 3, 12] , after calling your function, nums should is [1, 3, 12, 0, 0] .

Note:

      1. You must does this in-place without making a copy of the array.
      2. Minimize The total number of operations.

https://leetcode.com/problems/move-zeroes/

Put all of the 0 in the array to the end, and you cannot simply open an array again.

The first elegant approach, open a variable count=0, the array of nonzero number, in order to move to the subscript count of the position, each move a count++, the last to fill 0;

1 /**2 * @param {number[]} nums3 * @return {void} does not return anything, modify Nums in-place instead.4  */5 varMovezeroes =function(nums) {6     varCount = 0;7      for(vari = 0; i < nums.length; i++){8         if(Nums[i]!== 0){9Nums[count] =Nums[i];Tencount++; One         } A     } -      for(; count < nums.length; count++){ -Nums[count] = 0; the     }   -};

The second call to the powerful splice method, first record the position of the next 0, from the back to the 0 from the array to delete (from the trip will be disrupted subscript order), and finally completed.

1 /**2 * @param {number[]} nums3 * @return {void} does not return anything, modify Nums in-place instead.4  */5 varMovezeroes =function(nums) {6     varIndexarr =[], I;7      for(i = 0; i < nums.length; i++){8         if(Nums[i] = = = 0){9 Indexarr.push (i);Ten         } One     } A      for(i = indexarr.length-1; I >= 0; i--){ -Nums.splice (Indexarr[i], 1); -     } the      for(i = 0; i < indexarr.length; i++){ -Nums.push (0); -     } -};

[Leetcode] [JavaScript] Move Zeroes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.