-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoveZeros_hard.java
More file actions
executable file
·56 lines (51 loc) · 1.31 KB
/
MoveZeros_hard.java
File metadata and controls
executable file
·56 lines (51 loc) · 1.31 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package code.coder.lee.easy;
/**
* Created by bcc on 16/3/9.
*/
public class MoveZeros_hard {
public void moveZeroes(int[] nums) {
if (nums==null){
return;
}
for(int i=nums.length-1;i>=0;i--){
while(i>=0&&nums[i]!=0){
i--;
}
if(i>=0&&nums[i]==0){
for(int j=i ;j<nums.length-1;j++){
nums[j] = nums[j+1];
}
nums[nums.length-1] = 0;
}
}
}
public void moveZeroes1(int[] nums){
if(nums == null){
return;
}
int zeroNum = 0;
for(int i=0;i<nums.length;i++){
if(nums[i]==0){
zeroNum++;
}else{
nums[i-zeroNum] = nums[i];
}
}
while(zeroNum>0){
nums[nums.length-zeroNum] = 0;
zeroNum--;
}
}
public static void main(String[] args) {
MoveZeros_hard moveZeros = new MoveZeros_hard();
int[] nums = {1,0,0};
for (int i = 0;i<nums.length;i++){
System.out.print(nums[i]+ " ");
}
System.out.println();
moveZeros.moveZeroes1(nums);
for (int i = 0;i<nums.length;i++){
System.out.print(nums[i]+ " ");
}
}
}