查找向量中小于阈值(复杂度)的所有数字

时间:2014-09-23 10:11:25

标签: c++ sorting vector

v 成为unsorted大小n的向量,我们希望从中找到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;
}

问题:

  1. 第二种算法的复杂性是什么?
  2. 在c ++中有什么更好的方法呢?

1 个答案:

答案 0 :(得分:3)

执行该操作的惯用方法是copy_if(或remove_if),并且在未排序的向量上确实是O(n)

第二种解决方案需要对矢量进行排序,这几乎总会使复杂性变差;典型的排序算法在O(n log n)中工作(在最坏的情况下更接近n^2),而范围知识的算法在O(n)中工作。


相当简短直观的解释是,在任何给定的遍历点,因为你对前面的元素一无所知,你不能跳过它们,直到你检查所有元素为止。

相关问题