283. Move zeros
程序员文章站
2024-02-17 10:32:16
...
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.
For example, given
`nums = [0, 1, 0, 3, 12]`, after calling your function, `nuts` should be `[1, 3, 12, 0, 0]`.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
思路
- 将所有的非0数向前尽可能的压缩,最后把没压缩的那部分全置0就行了。比如nums = [0, 1, 0, 3, 12],先压缩成[1, 3, 12], 剩余的2个数为全置为0。
- 用一个指针记录压缩到的位置。
class Solution {
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) return;
int endNewArray = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[endNewArray] = nums[i];
endNewArray++;
continue;
}
}
for (; endNewArray < nums.length; endNewArray++) {
nums[endNewArray] = 0;
}
}
}
上一篇: 取出张量中的值
下一篇: 【Leetcode】66. 加一