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. See it on Leetcode
1
2
3
For example:
Given nums = [0, 1, 0, 3, 12]
It should return [1, 3, 12, 0, 0]
Hint
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Solution in Java, C++ and Javascript
java
cpp
js
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassSolution{ publicvoidmoveZeroes(int[] nums){ int count = 0; for (int index = 0; index < nums.length; index++) { if (nums[index] != 0) { nums[count++] = nums[index]; } } for (int i = count; i < nums.length; i++) { nums[i] = 0; } } }
1 2 3 4 5 6 7 8 9 10
class Solution { public: voidmoveZeroes(vector<int>& nums){ for (int lastNonZeroFoundAt = 0, cur = 0; cur < nums.size(); cur++){ if (nums[cur] != 0) { swap(nums[lastNonZeroFoundAt++], nums[cur]); } } } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var moveZeroes = function (nums) { var count = 0; for (var cur = 0; cur < nums.length; cur++) { if (nums[cur] !== 0) { var origin = nums[count]; nums[count] = nums[cur]; nums[cur] = origin; count++; } } };