23
loading...
This website collects cookies to deliver better user experience
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
[1,3,12,0,0]
as sorted in order with the zeroes moved to the end and so my first few times around, I sorted my nums
array before moving the 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.
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
nums
and have to take that array and leave everything as is except for any zeroes (0
), which we move to the end of the array. All this while not making a copy of the array.var moveZeroes = function(nums) {
let nonZero = 0;
};
nonZero
variable, let's loop through the nums
array to look for non-zeroes. We can accomplish this with a simple for
loop. If the current element in our array is not equal to zero (0
), we can set it to the current index of nonZero
and then increment nonZero
to keep going:var moveZeroes = function(nums) {
let nonZero = 0;
for(let i=0; i < nums.length; i++){
if(nums[i] !== 0){
nums[nonZero] = nums[i];
nonZero++;
};
};
nonZero
index and replace those elements with the appropriate zeroes and it looks a little something like this:for(let i = nonZero; i < nums.length; i++) {
nums[i] = 0;
};
var moveZeroes = function(nums) {
let nonZero = 0;
for(let i=0; i < nums.length; i++){
if(nums[i] !== 0){
nums[nonZero] = nums[i];
nonZero++;
};
};
for(let i = nonZero; i < nums.length; i++) {
nums[i] = 0;
};
};