查找向量中小于阈值的所有数字(复杂度)
Posted
技术标签:
【中文标题】查找向量中小于阈值的所有数字(复杂度)【英文标题】:Find all numbers in an vector that are less than a threshold (complexity) 【发布时间】:2014-09-23 10:11:25 【问题描述】:让 v 为大小为n
的unsorted
向量,我们希望从中找到所有Less Than
给定阈值delta
的数字。
第一个建议
#include <iostream>
#include <vector>
using namespace std;
int main()
vector<int> v = 5,12,2,3,10,122,45;
int delta = 5;
for(size_t i = 0; i < v.size();i++)
if(v[i] < delta)cout << v[i] << endl;
return 0;
对于第一个解决方案,复杂度是 O(n) 对吗?
第二个建议
#include <iostream>
#include <vector>
using namespace std;
int main()
vector<int> v = 5,12,2,3,10,122,45;
//Sort vector v
std::sort(v.begin(), v.end());
int delta = 5;
for(size_t i = 0; i < v.size();i++)
if(v[i] < delta)cout << v[i] << endl;
//I added the break since it's not important anymore to find all the numbers that are greater than `delta`/
else break;
return 0;
问题:
-
第二种算法的复杂度是多少?
在 c++ 中有什么更好的方法?
【问题讨论】:
对于未排序的向量,没有比O(n)
更好的解决方案了。
【参考方案1】:
这样做的惯用方法是copy_if
(或remove_if
),它确实是O(n)
在未排序的向量上。
第二种解决方案需要对向量进行排序,这几乎总是会使复杂度变差;典型的排序算法适用于O(n log n)
(在最坏的情况下会更接近n^2
),而知道范围的算法无论如何都适用于O(n)
。
相当简短而直观的解释是,在任何给定的遍历点中,由于您对前面的元素一无所知,因此您不能跳过它们,直到您检查所有元素为止。
【讨论】:
以上是关于查找向量中小于阈值的所有数字(复杂度)的主要内容,如果未能解决你的问题,请参考以下文章