-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoveZeroEnd
More file actions
37 lines (29 loc) · 750 Bytes
/
Copy pathMoveZeroEnd
File metadata and controls
37 lines (29 loc) · 750 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
35
36
class Solution {
public int[] moveZeroes(int[] nums) {
int lastNonZero = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int temp = nums[i];
nums[i] = nums[lastNonZero];
nums[lastNonZero] = temp;
lastNonZero++;
}
}
return nums;
}
}
// OverWrite Approach
public int[] moveZeroes(int[] nums) {
int index = 0;
// Move all non-zero elements to the front
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[index++] = nums[i];
}
}
// Fill the rest with 0s
while (index < nums.length) {
nums[index++] = 0;
}
return nums;
}