-
Notifications
You must be signed in to change notification settings - Fork 0
/
283. Move Zeroes
63 lines (44 loc) · 1.57 KB
/
283. Move Zeroes
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
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
Follow up: Could you minimize the total number of operations done?
题目翻译:
给定一个整数数组nums,将所有的0移动到数组的末尾,同时保持非零元素的相对顺序。注意,你必须在原地操作,不能拷贝数组。
示例1:
输入:nums = [0,1,0,3,12]
输出:[1,3,12,0,0]
示例2:
输入:nums = [0]
输出:[0]
约束:
数组长度在1到104之间。
数组元素的值在-2^31到2^31-1之间。
进一步要求:能否尽量减少操作次数?
public class Solution {
public void moveZeroes(int[] nums) {
// 初始化一个指针用于记录非零元素的下标
int nonZeroIndex = 0;
// 遍历数组,找到非零元素
for (int i = 0; i < nums.length; i++) {
// 如果当前元素不是0
if (nums[i] != 0) {
// 将非零元素放到指针所指的位置
nums[nonZeroIndex] = nums[i];
// 更新指针
nonZeroIndex++;
}
}
// 遍历数组,从指针所指的位置开始,将后面的元素都置为0
for (int i = nonZeroIndex; i < nums.length; i++) {
nums[i] = 0;
}
}
}