forked from algorithm020/algorithm020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoveZeroes.java
More file actions
40 lines (35 loc) · 915 Bytes
/
MoveZeroes.java
File metadata and controls
40 lines (35 loc) · 915 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
37
38
39
40
class Solution {
/**
* 两次遍历,第一次将所有非0元素往前移动,第二次将后面的数据补0
*
* @param nums
*/
public void moveZeroes(int[] nums) {
int startIndex = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[startIndex++] = nums[i];
}
}
for (int i = startIndex; i < nums.length; i++) {
nums[i] = 0;
}
}
/**
* 一次遍历
*
* @param nums
*/
public void moveZeroes1(int[] nums) {
int firstZeroIndex = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
//swap num
int temp = nums[firstZeroIndex];
nums[firstZeroIndex] = nums[i];
nums[i] = temp;
firstZeroIndex++;
}
}
}
}