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加一”新“数组的下一个元素等待被插入个人认为这种方式解释方式比较直观。

  • 相关阅读:
    mysql数据库-秒级别精度恢复数据、误删表恢复实现
    二进制安装MySQL
    mysql数据库-备份与还原-Percona XtraBackup 2.4备份工具使用
    2020-12-20 旋转图像
    第二章-SQL
    第二章-关系数据库
    Rust下载与安装
    2020-12-18 找不同
    第一章-数据库系统概述
    mysql-5.7安装配置
  • 原文地址:https://www.cnblogs.com/xiaoysec/p/4415604.html
Copyright © 2011-2022 走看看