算法 Java Leetcode

Move all 0’s to the end.

Question

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

  1. You must do this in-place without making a copy of the array.
  2. 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
public class Solution {
public void moveZeroes(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;
}
}
}