顺序统计量的选择
2015-12-10 10:40
183 查看
在选择顺序统计量中,期望的时间复杂度是O(n),主要是对于给定的数组,从其中选择出第k小的值。其与原理:利用了快速排序中的随机分割区间的函数,将第k小的值分割到一个区域里面,相当于把该问题划分的时候只划分了一个子问题,就没有O(lgn),根据快速排序的时间复杂度为O(nlgn)可知,其时间复杂度为O(n)。最坏运行时间为O(n*n),遇到很坏的情况下,每次都是划分到最大的数组中。对于分割后返回的位置值,用之与k比较大小,便知道了第k小的值所在的子数组位置,一直递归,便能求出该值。代码如下:
注意:temp2不能用temp+1代替。如果用,就会出错,因为二者在递归时begin并不相等,begin是一个变化的值,不是为0。他在statistic >temp2时begin就不为0了,十分重要。错误代码如下
int Insert::RandomSelect(vector<int> &coll,int begin,int end,int statistic)//statistic为第statistic小,而temp为下标,要比之小1 { if(begin==end) { return coll[begin]; } int temp=RandomPartition(coll,begin,end); int temp2=temp-begin+1; if(temp2==statistic) { return coll[temp]; } else if(statistic < temp2) { return RandomSelect(coll,begin,temp-1,statistic); } else { return RandomSelect(coll,temp+1,end,statistic-temp2); } }
注意:temp2不能用temp+1代替。如果用,就会出错,因为二者在递归时begin并不相等,begin是一个变化的值,不是为0。他在statistic >temp2时begin就不为0了,十分重要。错误代码如下
int Insert::RandomSelect(vector<int> &coll,int begin,int end,int statistic)//statistic为第statistic小,而temp为下标,要比之小1 { if(begin==end) { return coll[begin]; } int temp=RandomPartition(coll,begin,end); if(temp+1==statistic)//错误,会在某种情况下,循环递归,会导致栈溢出 { return coll[temp]; } else if(statistic < temp+1) { return RandomSelect(coll,begin,temp-1,statistic); } else { return RandomSelect(coll,temp+1,end,statistic-temp-1); } }
相关文章推荐
- android:scaleType属性解析
- 理解AngularJs指令
- 让CentOS默认生成core dump 当前用户
- 解码16进制Unicode编码字符串
- putty连接Amazon Ec2实例
- 关于STM32,新手需了解些什么?
- Longest Substring Without Repeating Characters
- Github readme语法-- markdown
- FP角度下的责任链模式(中间件模式,middleware)
- Forget Restclient and Embrace Postman for Rest API testing
- ubuntu server14.04 lnmp1.2 mysql添加innodb
- Java中抽象类和接口的用法和区别
- 【应用】信息短时存储
- Xcode Archive时卡住(hangle/stuck)问题
- 值得推荐的C/C++框架和库 (真的很强大)
- Linux服务器多端口配置
- CSS伪元素样式 :before 和 :after
- android studio的使用说明
- GitHub 上传地址
- eclipse myeclipse 查看java jdk源码