Skip to content

Commit 38e2f59

Browse files
committed
移动零 另解
1 parent e411be6 commit 38e2f59

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

283.移动零.java

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,18 +32,26 @@
3232
// @lc code=start
3333
class Solution {
3434
public void moveZeroes(int[] nums) {
35-
int count = 0;
35+
int i0 = 0;
36+
boolean find0 = true;
3637
for (int i = 0; i < nums.length; i++) {
37-
if (nums[i] == 0) {
38-
count++;
39-
} else {
40-
if (count > 0) {
41-
nums[i - count] = nums[i];
42-
nums[i] = 0;
43-
}
38+
if (find0 && nums[i] == 0) {
39+
i0 = i;
40+
find0 = false;
41+
continue;
42+
}
43+
if (!find0 && nums[i] != 0) {
44+
swap(nums, i, i0);
45+
i0++;
4446
}
4547
}
4648
}
49+
50+
private void swap(int[] nums, int i, int j) {
51+
int tmp = nums[i];
52+
nums[i] = nums[j];
53+
nums[j] = tmp;
54+
}
4755
}
4856
// @lc code=end
4957

0 commit comments

Comments
 (0)