283. Move Zeroes (E)

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

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

Note that you must do this in-place without making a copy of the array.

Example 1:

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

Example 2:

Input: nums = [0]
Output: [0]

Constraints:

  • 1 <= nums.length <= 104

  • -231 <= nums[i] <= 231 - 1

Follow up: Could you minimize the total number of operations done?

Solution:

Version 1:

比如说给你输入 nums = [0,1,4,0,2],你的算法没有返回值,但是会把 nums 数组原地修改成 [1,4,2,0,0]

结合之前说到的几个题目,你是否有已经有了答案呢?

题目让我们将所有 0 移到最后,其实就相当于移除 nums 中的所有 0,然后再把后面的元素都赋值为 0 即可。

所以我们可以复用上一题的 removeElement 函数:

void moveZeroes(int[] nums) {
    // 去除 nums 中的所有 0
    // 返回去除 0 之后的数组长度
    int p = removeElement(nums, 0);
    // 将 p 之后的所有元素赋值为 0
    for (; p < nums.length; p++) {
        nums[p] = 0;
    }
}

// 见上文代码实现
int removeElement(int[] nums, int val);

JAVA Version:
class Solution {
    public void moveZeroes(int[] nums) {
        
        int slow = 0; 
        int fast = 0;
        while(fast<nums.length)
        {
            if(nums[fast] == 0)
            {
                fast++;
            }
            else
            {
                nums[slow] = nums[fast];
                slow++;
                fast++;
            }
        }
        
        for(int i = slow; i< nums.length; i++)
        {
            nums[i] = 0;
        }
        
    }
}

Version 2:

public class Solution {
    public void moveZeroes(int[] nums) {
        
        int pos=0;
		
		for(int i=0;i<nums.length;i++)
		{
			if(nums[i]!=0)
			{
				nums[pos]=nums[i];
				pos++;
			}
		}
		
		for(;pos<nums.length;pos++)
		{
			nums[pos]=0;
		}
        
    }
}

Last updated