LeetCode – 283. Move Zeroes


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.

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

Note:

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

I didn't understand this problem at first; I thought I could just move it to the end. But then I realized the real challenge was maintaining the original order after the change. Luckily, the solution wasn't difficult.

public class Solution { public void moveZeroes(int[] nums) { int pos = 0; for(int i=0;i 

This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:「LeetCode – 283. Move Zeroes」

135
0 0 135

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top