快速选择算法
来源:互联网 发布:遗传算法参考书 编辑:程序博客网 时间:2024/06/10 00:11
快速选择算法可以在O(n)的复杂度下从数组找到符合条件的元素。
条件一般是要求返回第k大/小的数组元素。
程序执行过程如下:
1、选择一个pivot,将小于pivot的元素放入新数组A1,将大于pivot的元素放入新数组A2。
2、判断A1和A2的长度是否满足条件,如果满足,直接返回pivot。如果不满足,以A1或A2为参数进行递归调用。(这里是返回pivot还是返回别的数,以A1为参数递归还是以A2为参数递归需要具体问题具体分析)
证明时间复杂度是O(n):http://www.cs.yale.edu/homes/aspnes/pinewiki/QuickSelect.html (这里面也有通常情况下的伪代码)
举个例子:
要求返回数组中第k大的元素
public class Solution {public int findKthLargest(int[] nums,int k) {ArrayList A2 = new ArrayList();int pivot = nums[0];for (int i = 0; i < nums.length; i++)if (nums[i] > pivot)pivot = nums[i];for (int i = 0; i < nums.length; i++)if (nums[i] < pivot)A2.add(nums[i]);int[] array=new int[A2.size()];for(int i=0;i<array.length;i++)array[i]=Integer.parseInt(String.valueOf(A2.get(i))); if(k>(nums.length-array.length)) return findKthLargest(array,k-(nums.length-array.length)); else return pivot; }public static void main(String args[]) {int[] arr = { 1, 2, 4, 2, 5, 1, 6, 7 };Solution s = new Solution();int re = s.findKthLargest(arr, 2);System.out.println(re);}}
这个题目是刷leetcode时候遇到的。上面这个findKthLargest方法可以得到正确结果,但是不能通过。因为当数组很大的时候,由于使用了list会导致时间超过限制。需要进一步改进
0 0
- 快速排序->快速选择算法
- 快速选择算法
- TopK-快速选择算法
- 快速选择算法
- 快速选择排序算法
- 快速选择select算法
- 快速选择算法
- 快速选择算法
- 快速选择算法
- 快速选择算法
- 快速选择算法
- 算法分析:快速选择
- 快速选择算法
- 快速选择算法
- 快速选择算法
- 查找算法---快速选择算法
- 快速、选择、冒泡排序算法
- 随机化快速次序选择算法
- 用mac 调试andriod
- 设计模式之工厂模式
- 使用Gensim建立bow TFIDF LSI模型对文本相似度计算
- 我的Web开发实战总结(一)
- 第一次考试 与 第二次考试 的简单题 要点
- 快速选择算法
- 畅通工程续
- POJ 1703 Find them, Catch them(并查集的拓展)
- Java 多线程(七) 线程间的通信——wait及notify方法
- 【一】设计模式——单例模式(Singleton Pattern)
- Android MotionEvent中getX()和getRawX()的区别
- 阻塞I/O和非阻塞I/O
- live事件替代写法
- iOS NSString / NSData / char* 类型之间的转换