26. Remove Duplicates from Sorted Array题目和答案详解

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 







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值