leetcode (Move Zeroes)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/84435234

Title:Missing Number   283

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/move-zeroes/

1. 反其道行之

时间复杂度:O(n),三次for循环,但都是一层,最长的for循环需要遍历整个数组的长度。

空间复杂度:O(1),没有申请额外。

    /**
     * 反其道行之,不要把关注点放在0上,先把非0的数全部移到最前面,移完后,后面的直接赋值为0
     * @param nums
     */
    public static void moveZeroes(int[] nums){

        int j = 0;

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[j++] = nums[i];
            }
        }

        for (; j < nums.length; j++) {
            nums[j] = 0;
        }

        for (int i = 0; i < nums.length; i++) {
            System.out.println(nums[i]);
        }

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/84435234