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

    题目的要求大概是给定一个数组和一个值,删除数组中所有和该值相同的元素并返回一个新的长度

    说一下思路:

                   可以采用双指针,下标i循环数组,每次都让p_last下标与i一起遍历,当A[i]与给定的value相同的时候,p_last停止,数组长度-1,i继续走将下一个值赋给A[p_last],如果是A[i]与value不同的话,就让p_last+1

    具体的代码如下:

     1 class Solution {
     2 public:
     3     int removeElement(int A[], int n, int elem) {
     4        int length = n;
     5        int p_last = 0;
     6        for(int i=0;i<n;i++){
     7             A[p_last] = A[i];
     8             if(A[i] == elem)
     9                 length--;
    10             else
    11                 p_last++;
    12        }
    13        return length;
    14     }
    15 };

     或者可以有一个更加直观的理解:

          如下面的代码:

     1 class Solution {
     2 public:
     3     int removeElement(int A[], int n, int elem) {
     4        int length = n;
     5        int p_last = 0;
     6         for(int i=0;i<n;i++){
     7             if(A[i]==elem){
     8                 length--;
     9             }else{
    10                A[p_last] = A[i];
    11                p_last++;
    12             }
    13         }
    14        return length;
    15     }
    16 };

    p_last代表当前”新“数组的下标,i循环数组当A[i]!=elem时进行赋值,并将p_last加一”新“数组的下一个元素等待被插入个人认为这种方式解释方式比较直观。

  • 相关阅读:
    半平面交模板
    poj2420(模拟退火大法好)
    hdu4266(三维凸包模板题)
    三维凸包模板
    三维空间直线最近点对hdu4741
    3维计算几何模板
    hdu1174(3维射线与圆是否相交)
    重点记忆
    UNICODE,GBK,UTF-8区别
    AJAX 基础
  • 原文地址:https://www.cnblogs.com/xiaoysec/p/4415604.html
Copyright © 2011-2022 走看看