zoukankan      html  css  js  c++  java
  • [Leetcode] 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.

    题意:删除给定的数,然后返回新的长度。

    思路:这题的思路和sort colors差不多,是其简化版。大致的思路是:使用两个指针,指针l 指前,指针 r 指后,遍历数组,遇到给定的数,则将指针 l 指向的元素和r指向的元素交换,每交换一次r--一次,然后重新从指针l处重新遍历;若不是给定的数,则直接跳过即可。代码如下:

     1 class Solution {
     2 public:
     3     int removeElement(int A[], int n, int elem) 
     4     {
     5         int count=0;
     6         if(n<1) return 0;
     7         int l=0,r=n-1;
     8         while(l<=r)
     9         {
    10             if(A[l]==elem)
    11             {
    12                 swap(A[l],A[r])
    13                 r--;
    14                 count++;
    15             }
    16             else
    17                 l++;
    18         }
    19         return n-count;
    20     }
    21 };

    思路二:从前向后遍历数组,遇到给定数,记下其位置,将其和后面第一个不为给定数交换,即可。代码如下:

     1 class Solution
     2 {
     3 public:
     4     int removeElement(int A[],int n,int elem)
     5     {
     6         int count=0;
     7         for(int i=0;i<n;++i)
     8         {
     9             if(A[i]==elem)
    10                 count++;
    11             else if(count>0)  //避免多个连续
    12                 A[i-count]=A[i];
    13         }
    14         return n-count;
    15     }
    16 }
  • 相关阅读:
    [luogu p4447] [AHOI2018初中组]分组
    咕咕咕通知
    [luogu p3817] 小A的糖果
    [luogu p1228] 地毯填补问题
    [luogu p1259] 黑白棋子的移动
    [luogu p3612] [USACO17JAN]Secret Cow Code S
    [luogu p1990] 覆盖墙壁
    [luogu p1928] 外星密码
    [luogu p2036] Perket
    [luogu p2392] kkksc03考前临时抱佛脚
  • 原文地址:https://www.cnblogs.com/love-yh/p/7111837.html
Copyright © 2011-2022 走看看