Skip to content

Latest commit

 

History

History
43 lines (35 loc) · 1.04 KB

283. Move Zeroes.md

File metadata and controls

43 lines (35 loc) · 1.04 KB

leetcode-cn Daily Challenge on November 19th, 2020.


Difficulty : Easy

Related Topics : ArrayTwo Pointers


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

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

  • You must do this in-place without making a copy of the array.
  • Minimize the total number of operations.

Solution

  • mine
    • Java
      • Runtime: 0 ms, faster than 100.00%, Memory Usage: 39.2 MB, less than 17.70% of Java online submissions
        public void moveZeroes(int[] nums) {
            if (nums == null || nums.length == 0) {
                return;
            }
            int noZeroPos = 0;
            for (int num : nums)
                if (num != 0) nums[noZeroPos++] = num;
        
            while (noZeroPos < nums.length) nums[noZeroPos++] = 0;
        }