[LeetCode] Move Zeroes

283. 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.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int zero = 0, nonZero = 0, n = nums.size();
for(int i = 0; i < n and (nums[zero] or !nums[nonZero] or nonZero < zero); i++) {
if(nums[zero]) ++zero;
if(!nums[nonZero] or nonZero < zero) ++nonZero;
}
while(zero < n and nonZero < n) {
if(nonZero > zero) swap(nums[zero], nums[nonZero]);
while(nonZero < n and (!nums[nonZero] or nonZero < zero)) ++nonZero;
while(zero < n and nums[zero]) ++zero;
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/move-zeroes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.