LeetCode刷题实战283:移动零
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.
示例
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
解题
class Solution {
public void moveZeroes(int[] nums) {
if (nums == null || nums.length <= 1) {
return;
}
int idx = 0;
for(int i=0; i<nums.length; i++) {
if (nums[i] != 0) {
nums[idx] = nums[i];
idx++;
}
}
for (int i = idx; i < nums.length; i++) {
nums[i] = 0;
}
}
}
赞 (0)