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 5The 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