整数无序数组求第K大数(暴力|快排)
来源:互联网 发布:有了淘宝为啥还有天猫 编辑:程序博客网 时间:2024/05/29 18:03
时间限制:1S
空间限制:32768K
题目描述:
给定无序整数序列,求第K大的数,例如{45,67,33,21},第2大的数为45
输入描述:
输入第一行为整数序列,数字用空格分割,如:45 67 33 21
输入第二行为一个整数K,K在数组长度范围内,如:2
输出描述:
输出第K大的数,本例为第2大的数:45
示例:
输入
45 67 33 21
2
输出
45
思路:本题数据小直接暴力,求类似的题目可以用快排思想,代码中注释部分为排序求解
#include <iostream>using namespace std;const int Maxn = 1005;void swap(int a[Maxn], int l, int r){ int temp = a[l]; a[l] = a[r]; a[r] = temp;}int quickSort(int a[Maxn], int k, int l, int r){ if(l==r) return a[l]; int key = a[l]; int left = l, right = r; while(left<right) { while(a[right]<key && left<right) right--; if(left<right) swap(a, left, right); while(a[left]>=key && left<right) left++; if(left<right) swap(a, left, right); } a[left] = key; if(left==k) return a[left]; else if(left>k) return quickSort(a, k, l, left-1); else return quickSort(a, k, left+1, r);}int main(){ int a[Maxn], k; int count = 0; while(cin >> a[count++]); cout << quickSort(a, a[count-2]-1, 0, count-3) << endl; return 0;}/*45 67 33 212*///#include <iostream>//#include <algorithm>//using namespace std;//const int Maxn = 1005;////int cmp(const int& a, const int& b)//{// return a>b;//}////int main()//{// int a[Maxn], k;// int count = 0;// while(cin >> a[count++]);// sort(a, a+count-2, cmp);// cout << a[a[count-2]-1] << endl;// return 0;//}
0 0
- 整数无序数组求第K大数(暴力|快排)
- 快排思想 求第(前)k大数
- 寻找第k大数(快排思想)
- 寻找无序数组中的第K大数
- 寻找无序数组中的第K大数
- 寻找无序数组中的第K大数
- 查找无序数组中的第K个最小值[快排思想]
- 【滴滴笔试】利用快排找到一个无序的数组中的第K大的数
- 寻找无序数组中第k大的数——快排思想
- 滴滴_无序整数数组求第K大 && K小
- 快排划分思想的应用-求第k大数或者第k小的数(求前k大数或者前k小的数)
- 求数组中的K大数,快排思想(Java改…
- 无序数组求第K大
- POJ 2104 K-th Number(快排 or 平方分割 or 归并树—求区间第k大数)
- 求数组中第K大数
- 求数组的第k大数
- 寻找无序数组中的第K大数和前K大数
- 快排的思想求第K小的数
- java面试——数据库面试题
- iOS 【didFinishLaunchingWithOptions 方法瘦身】
- docker-compose.yml 语法说明【转】
- ES6
- 通过PL/SQL Developer导出数据库表不好用的解决方案之一:
- 整数无序数组求第K大数(暴力|快排)
- iOS 浅谈:深.浅拷贝与copy.strong
- (十三)RabbitMQ消息队列-VirtualHost与权限管理
- Web启动,停止Windows服务
- Shadow Brokers公布黑客工具,您准备好防御了吗?
- docker学习笔记01:Centos安装docker
- SHOI 2008 仙人掌图 BZOJ 1023
- android6.0 动态权限申请
- 近期状态