zoukankan      html  css  js  c++  java
  • 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:

    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 };
  • 相关阅读:
    闭包函数 (字符编码,文件处理,函数基础总结)
    函数参数详解
    文件处理及函数基础
    文件处理高级
    面向对象----反射
    正则表达式与re模块
    常用模块
    模块和包
    内置函数与匿名函数
    HDU
  • 原文地址:https://www.cnblogs.com/raichen/p/4930095.html
Copyright © 2011-2022 走看看