Remove Element删除数组元素并返回长度

本文介绍了一种高效的数组元素删除算法,通过两种不同的方法实现:一是使用双指针技巧,通过覆盖相同值的方式调整数组;二是利用vector容器的erase方法逐个删除指定值。这两种方法都避免了不必要的元素移动,提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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. 

给定一个数组和一个值,删除数组中所有和它相等的值,返回删除后新数组的长度。

数组元素的顺序可以改变。

解析:

找到相同的值后用数组末端的不等于val的值替换,可避免删除元素后数组元素的移动

实现代码:

             class Solution {
public:
    int removeElement(int A[], int n, int elem) {
         if(n==0)return 0; 
           int index = 0, end = n-1;  
           /*从头开始顺查找,找到等于val的值,用数组末端不等于val的值替换*/  
           while(index <= end)  
           {  
               if(A[index] == elem)  
               {  
                   if(A[end] != elem)/*找到相等值,用末尾不相等值替换*/  
                   {  
                       A[index++] = A[end--];  
                   }  
                   else/*末尾值相等,找到不等于val的值*/  
                   {  
                       --end;  
                   }  
               }  
               else  
               {  
                   ++index;  
               }  
           }  
           return index;  
    }
};

解法2:  利用 vector 的 erase 方法删除找到的元素,但是每次循环需要获取新的数组长度。

代码:

          

  1. class Solution {  
  2. public:  
  3.     int removeElement(vector<int>& nums, int val) {  
  4.        int numSize = nums.size();  
  5.        vector<int>::iterator it = nums.begin();  
  6.          
  7.        for(int i = 0; i < numSize;)  
  8.        {  
  9.            if(nums[i] == val)  
  10.            {  
  11.                nums.erase(it + i);  
  12.                numSize = nums.size();//删除元素后重新获取数组大小  
  13.            }  
  14.            else  
  15.            {  
  16.                ++i;  
  17.            }  
  18.        }  
  19.          
  20.        return nums.size();  
  21.     }  
  22. };  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值