原题
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.
Example:
Input:[0,1,0,3,12]Output:[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位置开始遍历数组,使用变量counti记录元素插入的位置。
下标为i的元素如果不为零:那么在counti位置上插入当前的元素,counti++。
如果为0:那么遍历下一个元素
java实现
class Solution {
public void moveZeroes(int[] nums) {
int counti = 0;
for(int i = 0;i<nums.length;i++){
if(nums[i] != 0){
if(counti < i){
nums[counti] = nums[i];
}
counti++;
}
}
if(counti != 0){
for(int m = counti; m<nums.length;m++){
nums[m] = 0;
}
}
}
}

423

被折叠的 条评论
为什么被折叠?



