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, nums should be [1, 3, 12, 0, 0].
public class Solution {
public void moveZeroes(int[] nums) {
int cnt = 0, pos = 0;
// 将非0数字都尽可能向前排
for(int i = 0; i < nums.length; i++){
if(nums[i] != 0){
nums[pos]= nums[i];
pos++;
}
}
// 将剩余的都置0
for(;pos<nums.length; pos++){
nums[pos] = 0;
}
}
}
點擊查看更多內容
1人點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦