首页 > 其他 > 详细

Move Zeroes

时间:2015-11-02 15:41:17      阅读:247      评论:0      收藏:0      [点我收藏+]

题目:

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.

解析:

自己写的代码

 1 class Solution {
 2 public:
 3     void moveZeroes(vector<int>& nums) {
 4         vector<int>::size_type i;
 5         for(i=0;i < nums.size();i++)
 6         {
 7             vector<int>::iterator it = find(nums.begin(),nums.end()-i,0);
 8             if(it == nums.end()-i)
 9                 break;
10             else
11             {
12                 nums.erase(it);
13                 nums.push_back(0);
14             }
15         }
16     }
17 };

最然通过了,但是时间长,感觉想法也比较笨,事实上通过一次遍历即可

 1 class Solution {
 2 public:
 3     void moveZeroes(vector<int>& nums) {
 4         int n = nums.size();
 5         int left = 0, right = 0;
 6         while (right < n){
 7             if (nums[right]){
 8                 nums[left] = nums[right];
 9                 left++;
10             }
11             right++;
12         }
13         while (left < n)
14             nums[left++] = 0;
15     }
16 };

 

Move Zeroes

原文:http://www.cnblogs.com/raichen/p/4930095.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!