Leetcode-283. Move Zeroes

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

项目描述:

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.

给定一个数组 nums,写一个函数让数组中所有为0的元素移到数组的末尾,并且保持非0元素的相对位置

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

方法1:

/**
* 时间复杂度:O(n)
*空间复杂度:O(n)
* @param nums
*/
public void moveZeroes_1(int[] nums) {

        ArrayList<Integer> list = new ArrayList<>();

        int size = nums.length;

        for (int i = 0; i < size; i++) {
            if (nums[i] != 0) {
                list.add(nums[i]);
            }
        }

        for (int i = 0; i < list.size(); i++) {
            nums[i] = list.get(i);
        }

        for (int i = list.size(); i < size; i++) {
            nums[i] = 0;
        }
    }

方法2:

    /**
     * 时间复杂度:O(n)
     * 空间复杂度:O(1)
     * @param nums
     */
    public static void moveZeroes_2(int[] nums) {

        int k = 0; // nums 中,[0...k)的元素均为非0元素
        int size = nums.length;

        // 遍历到第 i 个元素后,保证[0...i]中所有非0元素都按照顺序排列在[0...k)中
        // 同时,[k...i]为0
        for (int i = 0; i < size; i++) {
            if (nums[i] == 0) {
                swap(nums, i, k++);
            }
        }

    }

    private static void swap(int[] nums, int i, int k) {
        int temp = nums[k];
        nums[k] = nums[i];
        nums[i] = temp;
    }

方法3:

 /**
     * 时间复杂度:O(n)
     * 空间复杂度:O(1)
     * @param nums
     */
    public static void moveZeroes_3(int[] nums) {
        int k = 0; // nums 中,[0...k)的元素均为非0元素
        int size = nums.length;

        // 遍历到第 i 个元素后,保证[0...i]中所有非0元素都按照顺序排列在[0...k)中
        for (int i = 0; i < size; i++) {
            if (nums[i] != 0) {
                nums[k++] = nums[i];
            }
        }

        // 将 nums 剩余的位置放置为0
        for (int i = k; i < size; i++) {
            nums[i] = 0;
        }
    }

 

posted @ 2019-04-28 23:21  夏落若的博客  阅读(114)  评论(0编辑  收藏  举报