Skip to content

Commit c50923c

Browse files
committed
add 283
1 parent 74dac42 commit c50923c

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
| 136 | [Single Number][136] |
2323
| 350 | [Intersection of Two Arrays II][350] |
2424
| 66 | [Plus One][66] |
25+
| 283 | [Move Zeroes][283] |
2526

2627

2728
**其他**
@@ -44,3 +45,4 @@
4445
[136]: https://github.com/andavid/leetcode-java/blob/master/note/136/README.md
4546
[350]: https://github.com/andavid/leetcode-java/blob/master/note/350/README.md
4647
[66]: https://github.com/andavid/leetcode-java/blob/master/note/66/README.md
48+
[283]: https://github.com/andavid/leetcode-java/blob/master/note/283/README.md

note/283/README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# [Move Zeroes][title]
2+
3+
## Description
4+
5+
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.
6+
7+
For example, given nums = `[0, 1, 0, 3, 12]`, after calling your function, nums should be `[1, 3, 12, 0, 0]`.
8+
9+
**Note:**
10+
11+
1. You must do this in-place without making a copy of the array.
12+
1. Minimize the total number of operations.
13+
14+
## 思路
15+
遍历一次数组,如果不为 0 则从前往后依次写到数组。
16+
17+
## [完整代码][src]
18+
19+
```java
20+
class Solution {
21+
public void moveZeroes(int[] nums) {
22+
int len = nums.length;
23+
if (len < 2) return;
24+
25+
int k = 0;
26+
for (int i = 0; i < len; i++) {
27+
if (nums[i] != 0) {
28+
nums[k++] = nums[i];
29+
}
30+
}
31+
32+
for(; k < len; k++) {
33+
nums[k] = 0;
34+
}
35+
}
36+
}
37+
```
38+
39+
[title]: https://leetcode.com/problems/move-zeroes
40+
[src]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_283/Solution.java
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public void moveZeroes(int[] nums) {
3+
int len = nums.length;
4+
if (len < 2) return;
5+
6+
int k = 0;
7+
for (int i = 0; i < len; i++) {
8+
if (nums[i] != 0) {
9+
nums[k++] = nums[i];
10+
}
11+
}
12+
13+
for(; k < len; k++) {
14+
nums[k] = 0;
15+
}
16+
}
17+
18+
public static void main(String[] args) {
19+
Solution solution = new Solution();
20+
int[] nums = {0, 1, 0, 3, 12};
21+
solution.moveZeroes(nums);
22+
for (int i = 0; i < nums.length; i++) {
23+
System.out.print(i == 0 ? nums[i] : "," + nums[i]);
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)