zoukankan      html  css  js  c++  java
  • No.27 Remove Element

    No.27 Remove Element

    Given an array and a value, remove all instances of that value in place and return the new length.

    The order of elements can be changed. It doesn't matter what you leave beyond the new length.

    Tags: Array Two Pointers

    移除数组中所有的给定数字
    要求:原地移除,不能使用额外空间;返回新数组的长度;可以改变原始顺序

    典型的两指针

     
     1 #include "stdafx.h"
     2 #include <map>
     3 #include <vector>
     4 #include <iostream>
     5 using namespace std;
     6 
     7 class Solution
     8 {
     9 public:
    10     int removeElement(vector<int> &nums, int val)
    11     {//移除数组中所有的给定数字
    12      //要求:原地移除,不能使用额外空间;返回新数组的长度;可以改变原始顺序
    13         int size = nums.size();
    14         int count = 0;//计数当前val出现的次数
    15 
    16         for(int i=0; i<size; i++)
    17         {
    18             if(nums[i] == val)
    19                 count++;
    20             else
    21             {
    22                 if(count != 0)
    23                     nums[i-count] = nums[i];
    24             }
    25         }
    26         nums.erase(nums.begin()+size-count,nums.end());
    27         return size-count;
    28     }
    29 };
    30 
    31 int main()
    32 {
    33     Solution sol;
    34     int data[] = {1,2,2,3,3,2,1,7,9,10};
    35     vector<int> test(data,data+sizeof(data)/sizeof(int));
    36     for(const auto &i : test)
    37         cout << i << " ";
    38     cout << endl;
    39     cout<< boolalpha << sol.removeElement(test,2)<<endl;
    40         for(const auto &i : test)
    41         cout << i << " ";
    42     cout << endl;    
    43 }
  • 相关阅读:
    运算放大器
    阻抗模型
    mysql优化
    tomcat调优
    jvm调优
    springboot使用
    deploy工程到nexus
    Spring data elasticsearch使用
    kibana使用
    笔记
  • 原文地址:https://www.cnblogs.com/dreamrun/p/4569501.html
Copyright © 2011-2022 走看看