MrainW's Home

All things come to those who wait!

0%

LeetCode 283. Move Zeroes

Question

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

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

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) return;

int insertPos = 0;
for (int num: nums) {
if (num != 0) nums[insertPos++] = num;
}

while (insertPos < nums.length) {
nums[insertPos++] = 0;
}
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(1)

Welcome to my other publishing channels