最小的K个数
来源:互联网 发布:cc域名多少钱一年 编辑:程序博客网 时间:2024/05/21 17:22
题目:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
方法一 直接排序
通过对数组排序,可得到最小的K个数,时间复杂度O(N*lgN)
方法二 变异的快排
现在一个哨兵,对两次的进行筛选,大于哨兵的值再右侧,小于哨兵的值在左侧。
如果哨兵的位置index>K,对于[begin ~ index-1]再次快排。
如果哨兵的位置index<K,对于[index+1 ~ end]再次快排。
结果得到的最小的K个数不是有序的。
代码如下
import java.util.ArrayList;import java.util.Random;public class Solution {public static void main(String[] args) {Solution s = new Solution();ArrayList<Integer> result = s.GetLeastNumbers_Solution(new int[] { 0,1,1,1,1,1,1,1,5,1,1,0 }, 4);//ArrayList<Integer> result = s.GetLeastNumbers_Solution(new int[] { 4, 5, 1, 6, 2, 7, 3, 8 }, 6);System.out.println(result);}public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {ArrayList<Integer> result = new ArrayList<>();if (k <= input.length && k > 0) {quickSort(input, k, 0, input.length - 1);for (int i = 0; i < k; ++i)result.add(input[i]);}return result;}private void quickSort(int[] input, int k, int begin, int end) {// 终止条件if (begin >= end) return;// 选择哨兵Random random = new Random();int index = begin + random.nextInt(end - begin);int tmp = input[index];int i = begin, j = end;// 快排while (i < j) {while (i < j && input[i] < tmp)++i;input[index] = input[i];index = i;// 注意是 input[j] >= tmpwhile (i < j && input[j] >= tmp)--j;input[index] = input[j];index = j;}input[index] = tmp;if (index == k - 1)return;if (index > k - 1) {quickSort(input, k, begin, index - 1);} else {quickSort(input, k, index + 1, end);}}}
0 0
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的K个数
- 最小的k个数
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的k个数
- 最小的k个数
- iOS 编码 URL Data
- sar 命令行的常用格式
- cocos2d文件打包步骤
- 从 QA 到 EP (四)
- freopen
- 最小的K个数
- Selenium RC 简单实例 适用于新手刚刚接触
- do your test before you deliver your code to community
- 重心和质心的区别
- 机器学习搞的杀毒引擎
- word wps 宏,剪切板内容保存文件 文件首行为文件名称
- 找出最长的连续数字串
- 【C#】C#中单例的双重锁定模式
- 二叉树遍历的非递归算法