letecode [283] - 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.

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的元素移到数组末尾。要求在原数组上操作且移动的操作次数最少。

理  解:

  用两个指针i , j。指针i 遍历数组,每遇到一个不为0的数,赋值给j 指向的位置。遍历完后,新数组末尾用0补全长度。

  也可将第一个0与后面的非0元素交换位置实现。

代 码 C++:

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

运行结果:

  执行用时 :20 ms, 在所有C++提交中击败了93.39% 的用户

  内存消耗 :9.7 MB, 在所有C++提交中击败了5.49%的用户

posted @ 2019-06-15 10:12  lpomeloz  阅读(101)  评论(0编辑  收藏  举报