我在下面编写了C ++代码,找到了向量中丢失最多的正整数。但是,如果向量中存在重复值,则它不起作用。任何人都可以提出一种有效的方法来删除重复项而不对向量进行排序,因为逻辑取决于所维护的向量的顺序。
预期的最坏情况空间复杂度为O(N),超出输入存储空间(不包括输入参数所需的存储空间)。
FirstMissingPositive(std::vector<int> a) {
//size
int N = a.size();
// a dummy value to replace
// integers below 0 and above N
int FLAG = N + 2;
for (int i = 0; i < N; ++i) {
if (a[i] <= 0 || a[i] > N) {
a[i] = FLAG;
}
}
// Formula loop
for (int i = 0; i < N; ++i) {
if (a[i] == FLAG || a[i] == -FLAG) {
continue;
}
int value = abs(a[i]);
a[value - 1] = -abs(a[value -1]);
}
return N + 1;
}
答案 0 :(得分:1)
您可以删除重复项,但此方法的效率为O( n^2 )
。
这是一个示范程序。
#include <iostream>
#include <algorithm>
#include <vector>
template <typename ForwardIterator>
ForwardIterator remove_duplicates( ForwardIterator first, ForwardIterator last )
{
auto new_last = first;
for ( auto current = first; current != last; ++current )
{
if ( std::find( first, new_last, *current ) == new_last )
{
if ( new_last != current ) *new_last = *current;
++new_last;
}
}
return new_last;
}
int main()
{
std::vector<int> v = { 1, 3, 2, 1, 4, 3 };
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
v.erase( remove_duplicates( v.begin(), v.end() ), v.end() );
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
它的输出是
1 3 2 1 4 3
1 3 2 4
答案 1 :(得分:0)
您可以使用其他设置来标记唯一值:
#include <iostream>
#include <vector>
#include <set>
int main()
{
std::vector<int> v = { 1, 3, 2, 1, 4, 3 };
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
std::set<int> s;
for (auto iter = v.begin(); iter != v.end(); ) {
if (s.find(*iter) == s.end()) {
s.insert(*iter);
iter++;
}
else {
iter = v.erase(iter);
}
}
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
答案 2 :(得分:-2)