lintcode539 移动零

移动零 

给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序

 注意事项

1.必须在原数组上操作
2.最小化操作数

样例

给出 nums = [0, 1, 0, 3, 12], 调用函数之后, nums =[1, 3, 12, 0, 0].

 

 1 class Solution {
 2 public:
 3     /*
 4      * @param nums: an integer array
 5      * @return:
 6      */
 7     void moveZeroes(vector<int>& nums) {
 8         // write your code here
 9         vector<int> res;
10         int len = nums.size();
11         if (0 == len) return;
12         for (int i = 0; i < len; i++) {
13             if (nums[i] != 0) {
14                 res.push_back(nums[i]);
15             }
16         }
17         for (int i = res.size(); i < len; i++) {
18             res.push_back(0);
19         }
20         nums = res;
21     }
22 };

 

posted on 2017-10-06 20:11  狗剩的美丽家园  阅读(119)  评论(0编辑  收藏  举报

导航