26. Remove Duplicates from Sorted Array

Problem:

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.


这道题也是一道Easy的题,先是用一个数nowNumber保存数组第一个值,然后从第二个数开始,假如不等的话,nowNumber的值设为当前值,然后迭代器就+1。相等的话,就删除。这里要注意erase函数会使得迭代器失效,但是会返回下一个迭代器的值,所以需要用it = arr.erase(it). 


Code:(LeetCode运行结果49ms)

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() == 0) {
            return 0;
        }
        int nowNumber = nums[0];
        vector<int>::iterator it;
        for (it = nums.begin() + 1; it != nums.end(); ) {
            if (*it != nowNumber) {
                nowNumber = *it;
                it++;
            } else {
                //迭代器失效,erase会返回下一个迭代器,所以循环条件不能用it++。
                it = nums.erase(it);
            }
        }
        return nums.size();
    }
};


过了几天看回这道题,重新把这题分了类。这是一题关于线性表的操作题。然后重新思考一些新的解法。vector这是个好东西,它里面还有很多很有用的东西,例如:

int distance(iterator a, iterator b); //会返回迭代器a到迭代器b之间的距离。

iterator unique(iterator a, iterator b); //会把迭代器a到迭代器b之间的元素进行相邻去重的操作。

所以这里一行代码就能把这题做出来:


Code2:(LeetCode运行结果29ms)

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        return distance(nums.begin(), unique(nums.begin(), nums.end()));
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值