-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoveZeros.java
More file actions
34 lines (31 loc) · 908 Bytes
/
MoveZeros.java
File metadata and controls
34 lines (31 loc) · 908 Bytes
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
//time:o(n)
//space:o(1)
class Solution {
// num of operation : nums.length;
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) return;
int start = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[start++] = nums[i];
//nums[start]=nums[i];
//start++;
}
}
while (start < nums.length) {
nums[start++] = 0;
}
}
// num of operation : 2 * num of non-zero
// lots of zeros
public void moveZeroes2(int[] nums) {
if (nums == null || nums.length == 0) return;
for (int i = 0, j = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int temp = nums[i];
nums[i] = nums[j];
nums[j++] = temp;
}
}
}
}