码迷,mamicode.com
首页 > 其他好文 > 详细

nth_element学习

时间:2014-09-15 04:30:58      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   文件   

  今天学习到STL中的nth_element,她是一个默认能求第k小的数的方法,需要的头文件为algorithm。

  默认为:nth_element(start, start+n, end)

  使第n大元素处于第n位置(从0开始,其位置是下标为n的元素),并且比这个元素小的元素都排在这个元素之前,比这个元素大的元素都排在这个元素之后,但不能保证他们是有序的。

 

  

 1 #include <stdio.h>
 2 #include <algorithm>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int n,k;
 9     int a[10];
10     while(scanf("%d %d",&n, &k) == 2 )
11     {
12         for(int i=0; i<n; i++)
13             scanf("%d",&a[i]);
14         nth_element(a,a+k-1,a+n);
15         printf("%d\n",a[k-1]);
16         for(int i=0; i<n; i++)
17             printf("%d ",a[i]);
18         printf("\n");
19     }
20     return 0;
21 }

 

    当然,你还可以求第K大的数,方法即是添加一个greater<int>()参数,

 

 1 #include <stdio.h>
 2 #include <algorithm>
 3 #include <iostream>//这里需要添加iostream
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int n,k;
 9     int a[10];
10     while(scanf("%d %d",&n, &k) == 2 )
11     {
12         for(int i=0; i<n; i++)
13             scanf("%d",&a[i]);
14         nth_element(a,a+k-1,a+n,greater<int>());
15         printf("%d\n",a[k-1]);
16         for(int i=0; i<n; i++)
17             printf("%d ",a[i]);
18         printf("\n");
19     }
20     return 0;
21 }

 

 

bubuko.com,布布扣

 

如上图所示,我要求第2大的数,首先输出了4,这是对的!

然后,nth_element将4放在了第2个位置,比起大的,均在其前;比其小的,均在其后。但并不一定有序!

这也就造成了nth_element的O(n)的逆天复杂度。

nth_element学习

标签:style   blog   http   color   io   os   ar   for   文件   

原文地址:http://www.cnblogs.com/catdrivedragon/p/3972081.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!