Algorithm
Problem Name: 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.
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
Code Examples
#1 Code Example with C Programming
Code -
C Programming
void moveZeroes(int* nums, int numsSize) {
int i, j, k;
for (i = 0, j = 0; j < numsSize; j ++) {
if (nums[j] != 0) {
nums[i ++] = nums[j];
}
}
memset(&nums[i], 0, (j - i) * sizeof(int));
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
void moveZeroes(vector<int>& nums) {
for(int i = 0, j = 0; j < nums.size(); j++) if(nums[j] != 0) swap(nums[i++], nums[j]);
}
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Java Programming
Code -
Java Programming
class Solution {
public void moveZeroes(int[] nums) {
int startIdx = 0;
int endIdx = 0;
while (endIdx < nums.length) {
if (nums[endIdx] != 0) {
nums[startIdx++] = nums[endIdx];
}
endIdx++;
}
while (startIdx < nums.length) {
nums[startIdx++] = 0;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Javascript Programming
Code -
Javascript Programming
const moveZeroes = function(nums) {
const len = nums.length;
let l = len;
for (let i = 0; i < l; ) {
if (nums[i] === 0) {
nums.splice(i, 1);
nums.push(0);
l -= 1;
} else {
i += 1;
}
}
};
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with Python Programming
Code -
Python Programming
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i, items=0, 0
while i
Copy The Code &
Try With Live Editor
Input
Output
#6 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0283_MoveZeroes
{
public void MoveZeroes(int[] nums)
{
if (nums == null || nums.Length <= 1) return;
int cur = 0;
for (int i = 0; i < nums.Length; i++)
if (nums[i] != 0)
nums[cur++] = nums[i];
for (; cur < nums.Length; cur++)
nums[cur] = 0;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output