26. 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.
问题描述:
题目的要求是给定一个有序的数组,将数组里重复的元素去掉,函数的返回结果是去掉重复元素后的数组长度。
原本以为只要返回去掉重复元素后的数组长度,但是后来发现了同时要将重复的元素从原数组里去掉,因为可以看到题目给出的函数中数组是作为引用输入,所以函数返回之后数组也已经变成去重之后的数组。
解题思路:
因为题目给出的数组是已经排好序了,所以我们可以设定一个current表示上一个元素,当遍历到第i个元素nums[i]
- 如果nums[i]与current相同,表明nums[i]是重复的元素,将nums[i]从数组中去掉,继续访问下一个元素,current的值不变;
- 如果nums[i]与current不相同,表明已经没有与current相同的元素了,可以将nums[i]的值赋给current,继续访问下一个元素。
这里有一个需要注意的问题是如何从vector中去除某个元素,因为我用的iterator遍历vector,所以可以用erase来去除某个元素,这个函数的参数是需要去除的元素的iterator,返回被去除元素的下一个元素的iterator。
代码:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() == 0) {
return 0;
}
vector<int>::iterator it = nums.begin();
int current = *it;
it++;
while (it != nums.end()) {
if (current == *it) {
it = nums.erase(it);
continue;
}
else {
current = *it;
}
if(it == nums.end()) break;
it++;
}
return nums.size();
}
};
int main(int argc, const char * argv[]) {
int array[] = {1, 1, 1};
int count = sizeof(array) / sizeof(int);
vector<int> nums(array, array + count);
Solution sln;
cout << sln.removeDuplicates(nums) << endl;
return 0;
}