LeetCode-283
Links:https://leetcode.com/problems/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.
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.
思路:遍历一次,遇0删除,count计数,遍历完后,增加count个0在末尾.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Solution { public: void moveZeroes(vector<int>& nums) { int count = 0; for(int i=0;i<nums.size();) { if(nums.at(i)==0) { nums.erase(nums.begin()+i); count++; } else{ i++; } } for(int i=0;i<count;i++) { nums.push_back(0); } } }; |
【LeetCode】283.Move Zeroes