Leetcode 283. Move Zeroes

Gary Chiang
1 min readSep 2, 2021

--

[easy]

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?

[Java-Gary]

  1. if we don’t want to copy the another array, I will add another variable to track how many zeros we have
  2. During the scanning, if the number is not 0, we will replace it to the current index(no zero array)
  3. After we loop the array, we will add those zeros at the end of the array

4. since this is a void function, no need to return anything back

--

--

Gary Chiang
Gary Chiang

Written by Gary Chiang

CS new grad, 6 years experience related to supply chain management. Located in Bay area

No responses yet