/
_0283_MoveZeroes.java
54 lines (51 loc) · 1.47 KB
/
_0283_MoveZeroes.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.diguage.algorithm.leetcode;
import java.util.Arrays;
/**
* = 283. Move Zeroes
*
* https://leetcode.com/problems/move-zeroes/[Move Zeroes - LeetCode]
*
* 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.
*
* .Example:
* [source]
* ----
* Input: [0,1,0,3,12]
* Output: [1,3,12,0,0]
* ----
*
* *Note:*
*
* . You must do this *in-place* without making a copy of the array.
* . Minimize the total number of operations.
*
* @author D瓜哥, https://www.diguage.com/
* @since 2020-01-05 22:26
*/
public class _0283_MoveZeroes {
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Move Zeroes.
*
* Memory Usage: 38 MB, less than 93.01% of Java online submissions for Move Zeroes.
*/
public void moveZeroes(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
count++;
continue;
}
nums[i - count] = nums[i];
}
for (int i = nums.length - count; i < nums.length; i++) {
nums[i] = 0;
}
}
public static void main(String[] args) {
_0283_MoveZeroes solution = new _0283_MoveZeroes();
int[] a1 = {0, 1, 0, 3, 12};
solution.moveZeroes(a1);
int[] r1 = {1, 3, 12, 0, 0};
System.out.println(Arrays.equals(a1, r1) + " : " + Arrays.toString(a1));
}
}