美文网首页
283 Move Zeroes

283 Move Zeroes

作者: 烟雨醉尘缘 | 来源:发表于2019-08-02 11:23 被阅读0次

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:

Input: [0,1,0,3,12]
Output: [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全部移动到数组的最后,但是其他数字的相对位置不能变

1. 记录下有多少个0就行了

实际耗时:0ms

public void moveZeroes(int[] nums) {
    if (nums == null || nums.length == 0 || nums.length == 1) {
        return;
    }
    int cur = 0;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] != 0) {
            int temp = nums[cur];
            nums[cur++] = nums[i];
            nums[i] = temp;
        }
    }
}

  首先需要明白一点,我只需要盯着这些非零的数字,然后让他们和0所在的位置进行交换即可。可以看到代码里每个非0的数字都会导致cur++,而cur就是目前nums[i]这个数字应该在的位置。

时间复杂度O(n)
空间复杂度O(1)

拓展,如果我想让所有的0都在前面呢?
只需要在循环的判断语句中把不等于改成等于就行了。因为只需要知道目前nums[i]前面有多少个0,就能知道它应该放在哪里。

相关文章

网友评论

      本文标题:283 Move Zeroes

      本文链接:https://www.haomeiwen.com/subject/cpokdctx.html