• leetcode 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.

    这个题也非常简单,就是把vector中的元素删除,然后再在末尾插入就好。不过对于vector不熟悉的我,做起来还真是吃力哦。

    补充一些vector的知识:

    1.begin,end,rbegin,rend:如果begin与end的值相等,它们所表示的范围为空。

    begin() 指向vector起始位置迭代器

    end()   当前vector末尾元素的下一位置的迭代器

    rbegin()指向末尾的下一位置,而其内容为末尾元素的值

    rend()当前vector起始位置的逆迭代器

    2.删除某一值的元素

    erase函数:erase删除iterator指定的元素后返回的是该元素后的指针。所以我们删除元素要这样:erase(i++);或者i=erase(i);

    3.用数组初始化vector

    int int_array[] = {1, 2, 3, 4};
    
    std::vector<int> vec_int(int_array, int_array+4); 
     1 class Solution {
     2 public:
     3     void moveZeroes(vector<int>& nums) {
     4         int count=0;
     5         for(vector<int>::iterator i=nums.begin();i!=nums.end();){
     6             if(*i==0) {
     7             i=nums.erase(i);
     8             count++;}
     9             else i++;
    10             if(i==nums.end()) break;
    11         }
    12         for(int j=0;j<count;j++)
    13           {  nums.push_back(0);}
    14     }
    15 };
  • 相关阅读:
    koa mog
    sdl
    基于WindowImplBase 更简单 以及 可变大小的,才是标准的
    df
    ffplay vc
    开源1bo
    react学习前一部分
    0514 react路由
    nodejs 调用进程
    Ubuntu Linux, 不要弄什么 wine,龙井 或者什么等 QQ 了。
  • 原文地址:https://www.cnblogs.com/LUO77/p/4959312.html
Copyright © 2020-2023  润新知