283. Move Zeroes

https://leetcode.com/problems/move-zeroes/description/

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.

For 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.

Thoughts

把数组中非零元素移到前面。也就是第一个非零元素放到0位置,第二个非零在1...依次类推,因此用两个前后i和j指针分别对nums遍历和指向要插入的位置,当非零时插入到j并++。

Code

/*
 * @lc app=leetcode id=283 lang=cpp
 *
 * [283] Move Zeroes
 */

// @lc code=start
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        for (int i = 0, j = 0; i < nums.size(); ++i) {
            if (nums[i] == 0) continue;
            nums[j++] = nums[i];
            if (j <= i) nums[i] = 0;
        }
    }
};
// @lc code=end

class Solution {
    public void moveZeroes(int[] nums) {
        int pos = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[pos] = nums[i];
                if (i != pos) {
                    nums[i] = 0;
                }
                pos++;
            }
        }
    }
}

Analysis

做题耗时9min.

Errors:

  1. 以为非零都是正整数。

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

Last updated