【问题标题】:Finding certain highest value in an array在数组中找到某个最高值
【发布时间】:2014-08-06 18:50:03
【问题描述】:

我必须在数组中找到某个最高值(例如第五个最高值)。

我写了一个算法,但是时间太长了。任何想法如何使它更快?

    int tab[100];
    // cin tab;

    int position;
    cin>>position;
    //  for example i need to find fifth highest
    // value in an array.

    int temp=0;

    sort( tab, tab + 100, greater <int>() );

    for(int y=0; y<100; ++y)
    {
        if (tab[y]==tab[y+1])
            continue;
        else
        {
            temp++;
            if(temp==position)
                cout<<tab[y];
        }
    }

【问题讨论】:

  • std::nth_element 可能会大大加快速度。
  • 因为你在输入之后调用了排序,所以你是时间排序+你的算法。
  • 当所有元素都相同时,您拥有 UB(y+1 超出范围)。
  • 找到价值后,您可以break

标签: c++ arrays


【解决方案1】:

正如有人在 cmets 中提到的,如果您不想自己编写算法,那么使用 std:nth_element 是一种方法。

如果你想自己写,你可能想看看这篇文章:

Nth largest element in a binary search tree

它解释了如何在二叉搜索树中找到第 n 个元素。

二叉搜索树是什么的信息可以在维基百科上找到:

http://en.wikipedia.org/wiki/Binary_search_tree

这应该会给你一个很好的起点。

【讨论】:

  • OP 似乎管理重复值,所以std::nth_element 的使用并不是那么简单。
猜你喜欢
  • 2018-06-10
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 2022-01-12
  • 2019-10-10
  • 2011-08-29
相关资源
最近更新 更多