题
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
链接:https://leetcode.cn/leetbook/read/all-about-array/x9rh8e/
来源:力扣(LeetCode)
解
class Solution {
public void moveZeroes(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = 0; j < nums.length - i - 1; j++) {
int tmp = 0;
if (nums[j] == 0){
tmp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = tmp;
}
}
}
}
}
进阶
:::info 题目中要求不产生新的数组只对原数组进行操作,估应该选择交换排序,这里只使用了最简单的冒泡排序,要减少操作次数,可以选择优化冒泡排序或是其他的交换排序,例如快速排序或是堆排序 :::