力扣练习之移动零

我爱海鲸 2022-07-06 14:18:22 初级算法

简介初级算法

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-easy/x2ba4i/

解法一:

  public static void moveZeroes(int[] nums) {
        for (int i = 0; i < nums.length-1; i++) {
            for (int j = 0; j < nums.length; j++) {
                if (nums[j] == 0 && (j+1) < nums.length) {
                    int temp = nums[j];
                    nums[j] = nums[j+1];
                    nums[j+1] = temp;
                }
            }
        }
    }

思路:冒泡排序,每一次冒泡都会将0移动到数组的最后一位,冒泡完后,所有的0就会移动到最后,且不打乱原来的数组的顺序。

你好:我的2025