算法导论 Exercises 9.3-6
摘要:Problem Description:The kth quantiles of an n-element set are the k - 1 order statistics that divide the sorted set intok equal-sized sets (to within ...
阅读全文
posted @
2012-12-11 23:47
Snser
阅读(2650)
推荐(0)
算法导论 Exercises 9.3-9
摘要:Problem Description:Professor Olay is consulting for an oil company, which is planning a large pipeline running east to west through an oil field of n...
阅读全文
posted @
2012-12-03 15:27
Snser
阅读(1918)
推荐(0)
如何产生 [0, 2147483647] 之间的随机数
摘要:一、简介随机数是编程中经常要用到的东西,但很遗憾的是在windows下vc和MinGW中的 RAND_MAX 都是32767,也就是说调用系统的rand()函数只能产生范围在[0, 32767]之间的随机数。那如何得到范围达到[0, 2147483647]的随机数呢?二、最直观的方法最直接的想法显然是调用rand()生成更大区间的随机数,比如两个rand()相加或者相乘,但是,两个rand()相加时,越大的数出现的概率越高,因为2=2+0=1+1=0+2,而5=0+5=1+4=2+3=3+2=4+1=5+0;两个rand()相乘时,是永远不可能得到更大区间范围内的质数的,比如两个[0, 4]范
阅读全文
posted @
2012-11-20 20:12
Snser
阅读(2311)
推荐(0)
算法导论 Exercises 9.3-7
摘要:Problem Description:Describe an O(n)-time algorithm that, given a set of S of n distinct numbers and a positive integerd k ≤ n, determines the k numbers in S that are closest to the median of S.问题描述:有一个长为n的数组且数组元素互不相同,要求以O(n)的时间复杂度找到离数组中值最近(与中值的差的绝对值最小)的k个数(k ≤ n)。问题升级:题目要求是找离中值最近的 k 个数,这里做一下推广,找离数组
阅读全文
posted @
2012-11-07 20:41
Snser
阅读(461)
推荐(0)
算法导论 Chapter 9.3 Selection in worst-case linear time
摘要:问题描述:本节要求以最坏情况下O(n)的时间复杂度找到长度为n的数组中第 i 大的数。解决方案:《算法导论》上提供了一个算法,该算法实质上是利用了快排中划分的思想,但其通过一些比较复杂的预处理工作保证了快排划分的均匀,并且能够从理论上证明其最坏情况下的时间复杂度可以达到O(n)。算法步骤:1、如图所示,将n个数分成5个一组,共有⌊n/5⌋组。2、对⌈n/5⌉组(包括可能不到5个数的那组)的组内数据进行直接插入排序,排序完成之后,图中白色的数据即为组内数据的中位数。 并将这⌈n/5⌉个中位数挑出来,具体做法见后面的代码。3、递归调用本算法找到这⌈n/5⌉个中位数的中位数,假设它为图中的x。4、假
阅读全文
posted @
2012-11-01 22:57
Snser
阅读(2565)
推荐(0)
算法导论 Exercises 9.3-8
摘要:Problem Description:Let X[1...n] and Y[1...n] be two arrays, each containing n numbers already in sorted order.Give an O(lgn)-time algorithm to find the median of all 2n elements in array X and Y.问题描述:X和Y是两个长度均为n的已排序数组,现要求以O(lgn)的时间复杂度找到两个数组中所有2n个数的中值。(注:这里中值被定义为:对于奇数个数,排序后中间那个,或者对于偶数个数,排序后中间两个数下标较小
阅读全文
posted @
2012-10-28 23:18
Snser
阅读(832)
推荐(0)
#include
摘要:本文是后续文章中涉及到的基本函数源代码。001、生成随机数View Code 1 unsigned int latestRandNum = 1; 2 3 /*设置随机数种子*/ 4 void srandGLibC(unsigned int seed) 5 { 6 latestRandNum = (seed == 0 ? 1 : seed); 7 } 8 9 /*生成[0, 2147483647]之间的随机数*/10 int randGLibC(void)11 {12 int randNum = ((latestRandNum * 1103515245) + 12345) ...
阅读全文
posted @
2012-10-28 23:15
Snser
阅读(482)
推荐(0)