给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
方法1:从第一位开始,寻找数组中的非0数放在最前面
class Solution {
public void moveZeroes(int[] nums) {
for(int i =0 ;i < nums.length-1; i++){
if(nums[i]==0){
for(int j=i+1;j < nums.length; j++){
if(nums[j]!=0)
{
int temp =nums[i];
nums[i]=nums[j];
nums[j]=temp;
break;
}
}
}
}
}
}
方法2:
1.遍历数组把非零元素(假设有k个)按顺序存入数组的0至k-1位置上;
2.把原数组剩余未新赋值部分(k到n-1位置上)全设置为0;
class Solution {
public void moveZeroes(int[] nums) {
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[index] = nums[i];
index++;
}
}
for (; index < nums.length; index++) {
nums[index] = 0;
}
}
}
来源:CSDN
作者:Slayer_Zhao
链接:https://blog.csdn.net/qq_38905818/article/details/104114705