LeetCode 283. Move Zeroes

来源:互联网 发布:1688货源网淘宝店铺 编辑:程序博客网 时间:2024/06/07 05:55

问题描述:

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:

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

 void moveZeroes(vector<int>& nums)     {        int count = 0;          for (vector<int>::iterator it = nums.begin(); it != nums.end();)          {              if (*it == 0)              {                  nums.erase(it);                  count++;              }              else              {                  ++it;              }          }                    for (int i = 0; i < count; ++i)          {              nums.push_back(0);          }      }

网上的解法大多都是用两个计数器从头至尾遍历来解决的,这里直接用到容器的erase操作,西安删除位置为0的元素,在在末尾添加0

0 0
原创粉丝点击