给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。

链接:https://leetcode.cn/leetbook/read/all-about-array/x9rh8e/
来源:力扣(LeetCode)
image.png

  1. class Solution {
  2. public void moveZeroes(int[] nums) {
  3. for (int i = 0; i < nums.length - 1; i++) {
  4. for (int j = 0; j < nums.length - i - 1; j++) {
  5. int tmp = 0;
  6. if (nums[j] == 0){
  7. tmp = nums[j];
  8. nums[j] = nums[j+1];
  9. nums[j+1] = tmp;
  10. }
  11. }
  12. }
  13. }
  14. }

进阶

:::info 题目中要求不产生新的数组只对原数组进行操作,估应该选择交换排序,这里只使用了最简单的冒泡排序,要减少操作次数,可以选择优化冒泡排序或是其他的交换排序,例如快速排序或是堆排序 :::