283. Move Zeroes
https://leetcode.com/problems/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.
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.
--
Time - O(n)
Space - O(1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public void moveZeroes(int[] nums) { | |
int zeros = 0; | |
for (int i = 0; i < nums.length; i++) { | |
if (nums[i] == 0) { | |
zeros++; | |
continue; | |
} | |
if (zeros > 0) { | |
// Move non zero elem back by zeros | |
nums[i - zeros] = nums[i]; | |
nums[i] = 0; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public void moveZeroes(int[] nums) { | |
// i - last non zero element | |
int i = nums[0] == 0 ? -1 : 0; | |
while (i < nums.length - 1 && nums[i + 1] != 0) { | |
i++; | |
} | |
// initialize j - first zero element | |
for (int j = i + 1; j < nums.length; j++) { | |
// if next element after zero is non zero, float it to i + 1, set j + 1 0 | |
if (nums[j] == 0 && j < nums.length - 1 && nums[j + 1] != 0) { | |
i++; | |
nums[i] = nums[j + 1]; | |
nums[j + 1] = 0; | |
} | |
} | |
} | |
} |