快排法求第k大,复杂度为O(n) import com.sun.media.sound.SoftTuning; import java.util.Arrays; import java.util.Random; public class Main { int[] generate(int n) { Random random = new Random(); int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = rand…
(找第k大的数) 给定一个长度为1,000,000的无序正整数序列,以及另一个数n(1<=n<=1000000),接下来以类似快速排序的方法找到序列中第n大的数(关于第n大的数:例如序列{1,2,3,4,5,6}中第3大的数是4). #include <iostream> using namespace std; int a[1000001],n,ans = -1; void swap(int &a,int &b) { int c; c = a; a = b; b…
有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数.给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在.测试样例:[1,3,5,2,2],5,3 http://blog.csdn.net/hymanxq/article/details/51026818 public class 寻找第K大的数 { public static void main(String[] args) { // TODO Auto-generated method…
Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B. Example 1: Input: nums = [1,3,1] k = 1 Output: 0 Explanation: Here are all the pairs:…
Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B. Example 1: Input: nums = [1,3,1] k = 1 Output: 0 Explanation: Here are all the pairs:…
利用改进的快排方法 public class QuickFindMaxKValue { public static void main(String[] args) { int[] a = {8, 3, 4, 1, 9, 7, 6, 10, 2, 5}; System.out.println(findMaxValue(a, 0, a.length - 1, 2)); } private static int findMaxValue(int[] a, int lo, int hi, int ma…
int get_kth(int l,int r) { if (l==r) return a[r]; ]; while (i<j) { while (a[i]<mid) i++; while (a[j]>mid) j--; if (i<j) { swap(a[i],a[j]); i++; j--; } } if (k<=j) return get_kth(l,j); if (k>=i) return get_kth(i,r); }…
#include <iostream> #include <cassert> using namespace std; int selectKth(int a[],int start,int end,int k){ assert(start <= end && k <= end+); int left = start; int right = end; int pivotVal = a[left]; while(left < right){ whi…
The kth great number Xiao Ming and Xiao Bao are playing a simple Numbers game. In a round Xiao Ming can choose to write down a number, or ask Xiao Bao what the kth great number is. Because the number written by Xiao Ming is too much, Xiao Bao is feel…
//下面两种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…
递归 int find_kth(vector<int>& nums1, int begin1, int size1, vector<int>& nums2, int begin2, int size2, int k) { size1 = min(k, size1);//第k大最多只要前k个 size2 = min(k, size2); if (k == 1) { return min(nums1[begin1], nums2[begin2]); } if (size…
#include <stdio.h> int *ga; int galen; void print_a(){ ; i < galen; i++){ printf("%d ",ga[i]); } printf("\n"); } //k = di k da yuan su int quick_findk(int *a, int len, int k){ ) ]; int *p,*l,*r,tmp; p=&a[len-]; l=a; r=&…