//下面两种part效率比较:相同运算量下part比part2快5倍左右,part2写法简单但是效率低 #include "stdafx.h" #include <iostream> #include <stdio.h> using namespace std; int part(int *arr, int l , int r) { c_num += r - l; swap(arr[r],arr[l+rand()%(r-l)]); int q = r--; wh…
求一组N个数中的第k个最大者,设k=N/2. import java.util.Random; public class K_Max { /** * @param args */ //求第K大的数,保证K大于等于1,小于等于array.length/2哦 public static int TopK(int array[],int K) { int topk[] = new int [K]; for(int i = 0; i<topk.length;i++) topk[i] = array[i]…
问题描述 无序数组求第K大的数,其中K从1开始算. 例如:[0,3,1,8,5,2]这个数组,第2大的数是5 OJ可参考:LeetCode_0215_KthLargestElementInAnArray 堆解法 设置一个小根堆,先把前K个数放入小根堆,对于这前K个数来说,堆顶元素一定是第K大的数,接下来的元素继续入堆,但是每入一个就弹出一个,最后,堆顶元素就是整个数组的第K大元素.代码如下: public static int findKthLargest3(int[] nums, int k)…
传送门 The k-th Largest Group Time Limit: 2000MS   Memory Limit: 131072K Total Submissions: 8690   Accepted: 2847 Description Newman likes playing with cats. He possesses lots of cats in his home. Because the number of cats is really huge, Newman wants…
问题描述:给定一系列数{a1,a2,...,an},这些数无序的,现在求第k大的数. 看到这个问题,首先想到的是先排序,然后直接输出第k大的数,于是得到啦基于排序的算法 算法一: #include<iostream>#include<algorithm>using namespace std;bool cmp(int a, int b){ return a > b; }int main(){ int k; int a[9] = { 6, 5, 9, 8, 2, 1, 7, 3…
传送门 Description There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Exampl…
题目链接:第k个数 题意:求n个数中第k小的数 题解: //由快速排序算法演变而来的快速选择算法 #include<iostream> using namespace std; const int N=1e5+10; int a[N]; //k是整个区间中的第k小的数. void quick(int l,int r,int k) {//快速选择算法保证每次递归时都递归到答案所在的区间. int i=l-1,j=r+1,x=a[l+r>>1]; if(l>=r)return a…
题目:给定两个数组,这两个数组是排序好的,让你求这两个数组合到一起之后第K大的数. 解题思路: 首先取得数组a的中位数a[aMid],然后在b中二分查找a[aMid],得到b[bMid],b[bSt]到b[bMid]的数小于等于a[aMid],b[bMid+1]到b[bEd]大于等于a[aMid],这样数组a和数组b就被划分为了两个部分,第一个部分的数小于等于a[aMid],第二部分的数大于等于a[aMid],然后统计这两个区域数的个数,个数相加等于k就返回,否则重复二分查找.代码如下: def…
原创 利用到快速排序的思想,快速排序思想:https://www.cnblogs.com/chiweiming/p/9188984.html array代表存放数列的数组,K代表第K大的数,mid代表一趟快速排序后返回的基准记录下标: 一趟快速排序下来若基准记录存在的位置满足:array.length-mid==K,则说明array[mid]即是第 K大的数,若小于K,说明第K大的数在区间 [ left , mid-1 ],大于K说明在区间 [ mid+1,right ]: import jav…
根据http://www.cnblogs.com/zhjp11/archive/2010/02/26/1674227.html 博客中所总结的7种解法,我挑了其中的解法3和解法6进行了实现. 解法3: 利用快速排序的思想,从数组S中随机找出一个元素X,把数组分为两部分Sa和Sb.Sa中的元素大于等于X,Sb中元素小于X.这时有两种情况:           1. Sa中元素的个数小于k,则Sb中的第k-|Sa|个元素即为第k大数:           2. Sa中元素的个数大于等于k,则返回Sa…