寻找第k大数
来源:互联网 发布:php调用python接口 编辑:程序博客网 时间:2024/05/16 11:00
/************************************************************************* > File Name: k_fenshu.cpp > Author: wangzhicheng > Mail: 2363702560@qq.com > Created Time: Sun 18 Jan 2015 10:47:12 PM WSTThis is a free program, you can modify or redistribute it under the term of GNU ************************************************************************/// search the k_th max number// for example, 3, 0, 1, 2, the 1 max number is 3, the 2 max number is 2#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <time.h>#include <iostream>#include <vector>#include <algorithm>using namespace std;/* * @purpose:partition a array, this is generally included in quick sort * */int partition(vector<int>&v, int start, int end) {int i, j;int k;int tmp;i = start;j = end;tmp = v[i];while(i < j) {while(i < j && v[j] > tmp) j--;if(i < j) v[i++] = v[j];while(i < j && v[i] < tmp) i++;if(i < j) v[j--] = v[i];}v[i] = tmp;return i;}void find_k_max(vector<int>&v, int start, int end, int k_th, int &k_max) {int pivot;int k;if(start <= end) {pivot = partition(v, start, end);k = end - pivot + 1;if(k == k_th) k_max = v[k];else if(k > k_th) find_k_max(v, pivot + 1, end, k_th, k_max);else find_k_max(v, start, pivot - 1, k_th - k, k_max);}}int main() { int n;int k_th, k_max;int i;cout << "number = ";cin >> n;cout << "k_th = ";cin >> k_th;if(k_th < 1 || k_th > n) {cerr << "imput error...!" << endl;exit(1);}vector<int>v(n);for(i = 0;i < n;i++) {cout << i << " = ";cin >> v[i];}find_k_max(v, 0, n - 1, k_th, k_max);cout << "k_max = " << k_max << endl;return 0;}
0 0
- 寻找第k大数
- 寻找第K大数的方法
- 寻找第K大数方法总结
- 寻找无序数组中的第K大数
- 寻找无序数组中的第K大数
- 寻找第k大数(快排思想)
- POJ3579 Median 寻找第K大数
- SzNOI c016 : 寻找第K大数
- 寻找无序数组中的第K大数
- 寻找数组中第K大数
- 分治算法--寻找第k大数
- 寻找第K大数的方法
- 算法题/寻找第K大数
- 寻找数组第二大数和第K大数
- 寻找前K大数
- 寻找数组中第K大数---使用堆
- 寻找第k大数的N种解法
- 【算法】寻找数组第K大数算法总结
- 线性代数公开课链接
- android finishAffinity()
- 安卓适配碰到的一些问题
- Unity Application.GetStreamProgressForLevel 获取关卡的流进度语法复习
- Unity3D中网格合并示例研究
- 寻找第k大数
- bzoj 2073: [POI2004]PRZ
- HDOJ 1014 Uniform Generator
- LeetCode-Sort Colors
- c语言命名
- How does HTTP file upload work?
- android-async-http
- Android 自定义View步骤
- Codeforces Round #288 (Div. 2)