描述:
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 A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
代码1:
// LeetCode, Remove Duplicates from Sorted Array
// 时间复杂度 O(n) , 空间复杂度 O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
int index = 0;
for (int i = 1; i < nums.size(); i++) {
if (nums[index] != nums[i])
nums[++index] = nums[i];
}
return index + 1;
}
};
代码2:
// LeetCode, Remove Duplicates from Sorted Array
// 使用STL,时间复杂度 O(n),空间复杂度 O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
return distance(nums.begin(), unique(nums.begin(), nums.end()));
}
};
函数用法:
//distance主要是用来求两个迭代器之间的元素个数。
std::distance
template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance (InputIterator first, InputIterator last);
//advance()主要是用来使迭代器步进(或步退)n个元素;
void advance(pos,n);
unique()函数:
unique是STL中很实用的函数之一,需要#include iostream,下面来简单介绍一下它的作用。unique的作用是“去掉”容器中相邻元素的重复元素,这里去掉要加一个引号,为什么呢,是因为它实质上是一个伪去除,它会把重复的元素添加到容器末尾,而返回值是去重之后的尾地址(是地址!!)unique()是C++标准库函数里面的函数,其功能是去除相邻的重复元素(只保留一个),所以使用前需要对数组进行排序 ,下面的一个使用中已经给出该函数的一个使用方法,对于长度为n数组a,unique(a,a+n) - a返回的是去重后的数组长度
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 100000;
int a[N+5];
int main()
{
int n;
while (cin>>n)
{
for (int i = 0;i < n;++i)
{
scanf("%d",&a[i]);
}
sort(a,a+n);
n = unique(a,a+n) - a;//关键的一句
for (int i = 0;i < n;++i)
{
printf("%d ",a[i]);
}
puts("");
}
return 0;
}
代码3:(还没搞明白)
// LeetCode, Remove Duplicates from Sorted Array
// 使用STL,时间复杂度 O(n),空间复杂度 O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
return distance(nums.begin(), removeDuplicates(nums.begin(), nums.end(), nums.begin()));
}
template<typename InIt, typename OutIt>
OutIt removeDuplicates(InIt first, InIt last, OutIt output) {
while (first != last) {
*output++ = *first;
first = upper_bound(first, last, *first);
}
return output;
}
};