题目:Move Zeroes
题目的要求就是给一个数组,然后移除数组中所有元素为 0 的到数组的末尾处,在移除过程中不能改变其他非 0 元素的相对位置。
解答题目:
思路:
通过 for 循环遍历数组元素,当元素不为 0 就将其赋值给原数组第一位元素,以此类推,最后通过循环将 0 补到数组后面。
代码:
public void moveZeroes(int[] nums) {
int j = 0;
for(int i=0;i<nums.length;i++) {
if(nums[i]!=0) {
nums[j] = nums[i];
j++;
}
}
while(j<nums.length) {
nums[j++]=0;
}
}
运行截图: