Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/137.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 缩短运行时复杂性(c+;+;)_C++_Runtime - Fatal编程技术网

C++ 缩短运行时复杂性(c+;+;)

C++ 缩短运行时复杂性(c+;+;),c++,runtime,C++,Runtime,remove_dup函数的运行时复杂性为O(n^2),因为其中有两个嵌套的重复循环。我的任务是用O(n)得到相同的结果。 我真的不知道那会是什么样子 int add_without_dup (char x, vector<char>& r) {// pre-condition: assert (true) ; // post-condition: x is added to the end of r if it is not yet present in r /

remove_dup函数的运行时复杂性为O(n^2),因为其中有两个嵌套的重复循环。我的任务是用O(n)得到相同的结果。
我真的不知道那会是什么样子

 int add_without_dup (char x, vector<char>& r)
 {// pre-condition:
   assert (true) ;
 //  post-condition: x is added to the end of r if it is not yet present in r
//                  the result is the number of comparisons performed in this function
int i = 0 ;
while ( i < size(r) && r[i] != x )
    i++ ;
if ( i == size(r))
    r.push_back (x) ;
return i ;
}


int remove_dup (vector<char>& source, vector<char>& dest)

{// pre-condition:
assert (size (dest) == 0) ;
//  post-condition: dest is a copy of source without duplicate elements
//                  the result is the number of comparisons performed in this function
int nr_of_comparisons = 0 ;
for (int i = 0 ; i < size (source) ; i++)
    nr_of_comparisons += add_without_dup (source[i], dest) ;
return nr_of_comparisons ;
}
int add_而不使用_dup(char x、vector&r)
{//先决条件:
断言(正确);
//后置条件:如果x尚未出现在r中,则将x添加到r的末尾
//结果是在此函数中执行的比较次数
int i=0;
而(i<尺寸(r)&r[i]!=x)
i++;
如果(i==尺寸(r))
r、 推回(x);
返回i;
}
int remove_dup(矢量和源、矢量和目标)
{//先决条件:
断言(大小(dest)==0);
//post条件:dest是源的副本,没有重复的元素
//结果是在此函数中执行的比较次数
int nr_的_比较=0;
对于(int i=0;i
因为您的字符只能有256个可能的值,所以您可以保留一个
布尔数组[256]
。在中插入内容时,将该值设置为true。当您想要检查它是否在中时,您需要检查该值是否设置为true


复杂性是
O(N+S)
,其中S是您希望在向量中包含的可能值的数量。通常,对于char,
N>>S
,因此S无关紧要。

因为您的char只能有256个可能值,所以您可以保留一个
bool数组[256]
。在中插入内容时,将该值设置为true。当您想要检查它是否在中时,您需要检查该值是否设置为true


复杂度为
O(N+S)
,其中S是要在向量中包含的可能值的数量。通常,对于char,
N>>S
,因此S无关紧要。

如果可能,首先对内容进行排序。更好的方法是,只需查找
std::set
。我会看一看,谢谢。@JerryCoffin:如果你开始排序序列,我不确定你会如何得到一个O(n)算法。也就是说,我没有看到一个O(n)算法来删除重复项。@Dietmar使用无序的_集,你可以得到O(n)的平均时间。或者下面是索林的一个不错的破解。如果可能的话,先对内容进行排序。更好的方法是,只需查找
std::set
。我会看一看,谢谢。@JerryCoffin:如果你开始排序序列,我不确定你会如何得到一个O(n)算法。也就是说,我没有看到一个O(n)算法来删除重复项。@Dietmar使用无序的_集,你可以得到O(n)的平均时间。或者下面是索林的好黑客,非常好。非常感谢你!(非常好。非常感谢!但是不能给你一个放弃的悲伤:(