LeetCode-283:Move Zeroes (将数组中0元素移至尾部)

来源:互联网 发布:小学四年级体测数据 编辑:程序博客网 时间:2024/06/06 02:02

Question

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.

example:

given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

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

问题解析:

给定数组,将数组中的0元素移至数组末尾,非零元素顺序不变。注意在O(1)的空间复杂度内完成。

Answer

Solution 1:

加入位置指针,遍历赋值实现。

  • 因为在题目中说明,非零元素顺序不变,所以这不构成一个排序问题;
  • 加入一个数组位置指针,判断是否为0元素,不为0则赋值当前遍历的元素,位置指针自增1;否则跳过。
class Solution {    public void moveZeroes(int[] nums) {        if (nums == null || nums.length == 0) return;        int index = 0;        for (int num : nums){            if (num != 0){                nums[index++] = num;            }        }        while (index < nums.length){            nums[index++] = 0;        }        return;    }}
  • 时间复杂度:O(n),空间复杂度:O(1)
原创粉丝点击