-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q4_移动零.java
68 lines (59 loc) · 1.56 KB
/
Q4_移动零.java
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
57
58
59
60
61
62
63
64
65
66
67
68
package com.algorithm.demo.array;
import com.algorithm.demo.PrintArray;
/**
* 539. 移动零
* 给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序
* <p>
* 样例
* Example 1:
* <p>
* Input: nums = [0, 1, 0, 3, 12],
* Output: [1, 3, 12, 0, 0].
* Example 2:
* <p>
* Input: nums = [0, 0, 0, 3, 1],
* Output: [3, 1, 0, 0, 0].
* 注意事项
* 1.必须在原数组上操作
* 2.最小化操作数
*/
public class Q4_移动零 {
public static void main(String[] args) {
int[] what = {0, 1, 0, 3, 12};
moveZeroes2(what);
}
public static void moveZeroes2(int[] nums){
int position = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] != 0){
nums[position] = nums[i];
if(position != i){
nums[i] = 0;
}
position++;
}
}
PrintArray.print(nums);
}
/**
* @param nums: an integer array
* @return: nothing
*/
public static void moveZeroes(int[] nums) {
// write your code here
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {//不为 0 移动到数组前方
nums[count] = nums[i];
count++;
}
}
for (int i = count; i < nums.length; i++) {//数组后方补0
nums[i] = 0;
}
PrintArray.print(nums);
}
//1. loop , count zeros
//2. 开启新数组 loop
//3. index直接操作
}