[每日LeetCode] 283. Move Zeroes

  |   0 评论   |   626 浏览

Description:

Given an arraynums, write a function to move all0'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:

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

思路:本题要求移除数组中存在的0,要求不占用额外空间且尽量使用较少的步骤。考虑遍历数组,增加一个变量表示非0的元素,把非0元素和前面的0互换。


C++代码

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        for (int i=0,j=0; i<nums.size(); i++){
            if(nums[i])
                swap(nums[i],nums[j++]);
        }
    }
};

运行时间:16ms

运行内存:9.4M

评论

发表评论