zoukankan      html  css  js  c++  java
  • nth_element() O(n)复杂度求第k+1小元素

    nth_element() O(n)复杂度求第k+1小元素

    函数原型

    void nth_element(_RAIter, _RAIter, _RAIter);
    void nth_element(_RAIter, _RAIter, _RAIter, _Compare);
    void nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth,
    		_RandomAccessIterator __last)
    void nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth,
    		_RandomAccessIterator __last, _Compare __comp)
    

    先看官方的声明

    void nth_element(_RAIter, _RAIter, _RAIter);
    

    /*

    @brief Sort a sequence just enough to find a particular position

    using a predicate for comparison.

    @ingroup sorting_algorithms

    @param __first An iterator.

    @param __nth Another iterator.

    @param __last Another iterator.

    @param __comp A comparison functor.

    @return Nothing.

    Rearranges the elements in the range @p [__first,__last) so that @p *__nth is the same element that would have been in that position had the whole sequence been sorted. The elements either side of @p *__nth are not completely sorted, but for any iterator @e i in the range @p [__first,__nth) and any iterator @e j in the range @p [__nth,__last) it holds that @p__comp(*j,*i) is false.

    */

    请注意这句话

    so that @p *__nthis the same element that would have been in that position had the whole sequence been sorted.

    函数作用后*_nth的位置的值 与 排序之后*nth的值相等

    那么我们要求数组a中第k小的值,第二个参数就应该填a+k-1

    #include<algorithm>
    #include<iostream>
    using namespace std;
    int main()
    {
        int a[]={1,5,6,7,50,0,3,6,98,4,6,57,17,71,2,100};
        vector<int>aa(a,a+16);
        sort(aa.begin(),aa.end());
        for(auto i:aa)
            cout<<i<<" ";
        cout<<endl;
        nth_element(a,a+10,a+16);//a[10]的位置的值是排序之后a[10]的值 即第10+1小的位置
        for(auto i:a)
            cout<<i<<" ";
        cout<<endl;
    }
    
    

    或者可以写成一个函数

    #include<algorithm>
    #include<iostream>
    using namespace std;
    int GetNthVal(int *first,int *last,int k)/*第一小是最小,作用:求[first,last)中第k小的值*/
    {
        if(k>last-first)
            return -1;
        nth_element(first,first+k-1,last);
        return first[k-1];
    }
    int main()
    {
        int a[]={1,5,6,7,50,0,3,6,98,4,6,57,17,71,2,100};
        vector<int>aa(a,a+16);
        sort(aa.begin(),aa.end());
        for(auto i:aa)
            cout<<i<<" ";
        cout<<endl;
        cout<<GetNthVal(a,a+16,15);//求数组a中 第15小的值
    }
    
    
  • 相关阅读:
    rzchecktree用作类别权限的问题
    VirtualStringTree 动态建树/Checktree
    一键处理打印机因任务不能取消,无法接着打印
    Delphi从Internet下载文件
    仿迅雷客户端的浏览器自定义协议的小程序
    用最少的代码为你的窗体实现剪贴板操作
    delphi2010获取鼠标指向窗口的位置及鼠标在窗口内的相对位置坐标
    datasnap 上传/下载大文件(本Demo以图传片文件为例)
    dephi中用idhttp提交cookie
    delphi2010 向另一个窗口发送鼠标点击事件
  • 原文地址:https://www.cnblogs.com/dchnzlh/p/10427231.html
Copyright © 2011-2022 走看看