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

    27. Remove Element

    • Total Accepted: 129784
    • Total Submissions: 372225
    • Difficulty: Easy

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

    Do not allocate extra space for another array, you must do this in place with constant memory.

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

    Example:
    Given input array nums = [3,2,2,3]val = 3

    Your function should return length = 2, with the first two elements of nums being 2.

    思路:遇到val等值的数就删除。


    代码:

    这个适合于不改变原来数的顺序和位置的情况:

     1 class Solution {
     2 public:
     3     int removeElement(vector<int>& nums, int val) {
     4         int i;
     5         for(i=0;i<nums.size();){
     6             if(nums[i]==val){
     7                 nums.erase(nums.begin()+i);
     8                 continue;
     9             }
    10             i++;
    11         }
    12         return nums.size();
    13     }
    14 };

    实际上,本题可以改变原来数的顺序,所以下面的写法也可以:

    写法一:begin指针只记录可以留下的数。

     1 class Solution {
     2 public:
     3     int removeElement(vector<int>& nums, int val) {
     4         int begin=0,i=0;
     5         while(i<nums.size()){
     6             if(nums[i]!=val){
     7                 nums[begin++]=nums[i];
     8             }
     9             i++;
    10         }
    11         return begin;
    12     }
    13 };

    写法二:将当前最后的元素替换掉确认已经重复的元素,再对置换后的数进行判断。

     1 class Solution {
     2 public:
     3     int removeElement(vector<int>& nums, int val) {
     4         int i=0,n=nums.size();
     5         while(i<n){
     6             if(nums[i]==val){
     7                 nums[i]=nums[--n];
     8             }
     9             else{
    10                 i++;
    11             }
    12         }
    13         return n;
    14     }
    15 };

    写法三:用count记录所有的不符合要求的数。

     1 class Solution {
     2 public:
     3     int removeElement(vector<int>& nums, int val) {
     4         int count=0,i,n=nums.size();
     5         for(i=0;i<n;i++){
     6             if(nums[i]==val){
     7                 count++;
     8             }
     9             else{
    10                 nums[i-count]=nums[i];
    11             }
    12         }
    13         return n-count;
    14     }
    15 };
  • 相关阅读:
    MongoDB 常用的基础命令
    window.crypto 生成随机数
    正则去除object中key的引号
    git 常用操作命令
    常用的用于操作 css 的方法
    angular ViewChild ContentChild 系列的查询参数
    angular 键盘事件绑定与过滤
    mysql性能优化(A)
    移动硬盘写保护处理
    expdp/impdp导入导出
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5678617.html
Copyright © 2011-2022 走看看