您的位置:首页 > 其它

[leetcode26] Remove Duplicates from Sorted Array

2016-09-25 21:06 423 查看

Remove Duplicates from Sorted Array

从有序数组中取出重复数字

题目描述

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级别的,这道题目有一个知识点:也就是iterator的erase方法

其中,对 list 和 vector 来说,它们的 erase 函数会返回下一个迭代器。

因此在遍历时,只需要 it = nums.erase(it); 即可。

对 map 和 set 来说,它们的 erase 函数返回的 void,而在进行 erase 之后,当前迭代器会失效,无法再用于获取下一个迭代器。因此需要 erase 之前就获取指向下一个元素的迭代器。

那么这里我们有一种简便的方法:it = nums.erase(it++);(先创建副本,在调用erase方法,然后递增,然后副本返回赋值)

我的解答

//
//  main.cpp
//  leetcode26
//
//  Created by 李林 on 16/9/25.
//  Copyright © 2016年 lilin. All rights reserved.
//

#include <iostream>
#include <vector>
#include <iterator>
using namespace std;

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int previousNum = 0x7fffffff;

for(vector<int>::iterator it = nums.begin(); it!=nums.end(); ){
if(*it == previousNum){
it = nums.erase(it);    // 返回下一个迭代器指针
}else{
previousNum = *it;
it++;                   // 手动++
}
}

return nums.size();
}
};

int main() {
Solution s;
vector<int> nums;
int array[2] = {1, 1};
for(int i=0; i<2; i++)  nums.push_back(array[i]);

int result = s.removeDuplicates(nums);
printf("%d", result);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode array vector