1 题目简述
Given a sortedarray, remove the duplicates in-place such that each element appear only onceand return the new length.
给定一个排序数组,删除重复的位置,使每个元素只出现一次,并返回新的长度。
Do not allocateextra space for another array, you must do this by modifying the input arrayin-place with O(1) extra memory.
不要为另一个数组分配额外的空间,您必须通过使用O(1)额外内存来修改输入数组来实现这一点。
Example:
Given nums = [1,1,2],
Your function should return length = 2,with the first two elements ofnums being 1 and 2 respectively.
It doesn't matter what you leave beyond thenew length.
你的函数应该返回长度=2,而nums的前两个元素分别是1和2。
新长度以外的内容无所谓是什么样子。
2 答案详解
(1) 解决思想
本次解答采用C++编写,C++相对于C语言的一个重要的特点是:面向对象编程(OOP),故我们采用类的方法来实现所述要求。
很容易可以想到,遍历有序数组时,若遇到当前元素==后一个元素时,可以删除后一个元素;否则继续往后遍历。根据题目输入一个vector,而vector模板包含成员函数erase(),故遇到当前元素==后一个元素时,对后一个元素执行erase()操作来删除。
(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_;
public:
Solution(vector<T>& nums):nums_(nums) {}
int RemoveDuplicates();
};
template<class T>
int Solution<T>::RemoveDuplicates()
{
if(nums_.size() < 2) {
return nums_.size();
}
typename vector<T>::iterator it = nums_.begin();
while(it != nums_.end()-1) {
if(*it == *(it + 1)) {
nums_.erase(it + 1);
} else {
it++;
}
}
return nums_.size();
}
void Display(const int& data)
{
cout << data << ' ';
}
int main()
{
int arr[] = {1,1,1,2,2,3,4,5,6,6};
vector<int> nums(arr,arr + 10);
cout << "The size of init array:" << nums.size() << endl;
cout << "The init array:" ;
for_each(nums.begin(),nums.end(),Display);
cout << endl;
Solution<int> sol(nums);
cout << "After remove duplicates,the size of new array:" << sol.RemoveDuplicates() << endl;
cout << "The new array:";
for_each(nums.begin(),nums.end(),Display);
cout << endl;
}
程序运行结果为:
The size of init array:10
The init array:1 1 1 2 2 3 4 5 6 6
After remove duplicates,the size of new array:6
The new array:1 2 3 4 5 6