27. Remove Element题目和答案详解

本文介绍了一种使用 C++ 实现的高效方法来删除数组中特定值的所有实例,并保持 O(1) 的额外空间复杂度。通过双指针技巧,文章详细解释了如何在不使用额外数组的情况下完成这一任务。

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

1 题目简述

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 by modifyingthe input array in-place withO(1) extra memory.

不要为另一个数组分配额外的空间,您必须通过使用O(1)额外内存来修改输入数组来实现这一点。

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

元素的顺序可以改变。新长度以外的内容无所谓是什么样子。

Example:

Given nums = [3,2,2,3],val =3,

 

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

你的函数应该返回长度=2,而nums的前两个元素是2。

2 答案详解

(1) 解决思想

  本次解答采用C++编写,C++相对于C语言的一个重要的特点是:面向对象编程(OOP),故我们采用类的方法来实现所述要求。

  首先,设置两个下标i,j用于遍历数组,并赋予初值为0。

  然后,用j遍历数组,当遇到要删除的值的时候,不做操作继续遍历;而遇到不需要删除的值时,将下标为i的元素赋值为该值,并使得i++。直到遍历完整个数组为止。

  最后,删除从下标为i+1开始到数组结尾的元素。根据题目所需返回的长度即为i或者当前的数组长度size。

(2) 设计程序

  所设计的程序采用类模板实现,程序如下:

#include <iostream>
#include <vector>
#include <algorithm>

using std::cout;
using std::endl;
using std::vector;

template<class T>
class Solution
{
private:
    vector<T>& nums_;
    T val_;
public:
    Solution(vector<T>& nums,const T& val):nums_(nums),val_(val) {}
    int RemoveElement();
};

template<class T>
int Solution<T>::RemoveElement()
{
    int i(0);
    for(int j = 0; j < nums_.size(); j++) {
        if(nums_[j] != val_) {
            nums_[i++] = nums_[j];
        }
    }
    nums_.erase(nums_.begin() + i,nums_.end());
    return i;
}

void Display(const int& data)
{
    cout << data << ' ';
}

int main()
{
    int arr[] = {1,3,2,2,3,4,4,6,8,3,5};
    vector<int> nums(arr,arr + 11);
    cout << "The init array:";
    for_each(nums.begin(),nums.end(),Display);
    cout << endl << "The size of the init array:" << nums.size();
    Solution<int> sol(nums,3);
    int new_size = sol.RemoveElement();
    cout << endl << "The new array:";
    for_each(nums.begin(),nums.end(),Display);
    cout << endl << "After remove the element,the size of the new array:" << new_size << endl;
}

程序运行结果为:

The init array:1 3 2 2 3 4 4 6 8 3 5 
The size of the init array:11
The new array:1 2 2 4 4 6 8 5 
After remove the element,the size of the new array:8



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值