牛客网刷题之最小的K个数
来源:互联网 发布:jsp 视频网站源码 编辑:程序博客网 时间:2024/05/18 06:19
题目描述:
解题思路:
首先向导的是快排,然后取前k个数就可以了:
题解:
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) { ArrayList<Integer> list = new ArrayList<>(); if(input.length == 0 || input.length < k || k < 0){ return list; } quickSort(input , 0 , input.length-1); for(int i = 0 ; i < k ; ++ i){ list.add(input[i]); } return list; } private void quickSort(int[] input, int left, int right) { if(left >= right){ return; } int first = left; int last = right; int key = input[first]; while(first < last){ while(first < last && input[last] >= key){ last --; } input[first] = input[last];//小数移至左边 while(first < last && input[first] <= key){ first ++; } input[last] = input[first];//大数移至右边 } input[first] = key; quickSort(input, left, first-1); quickSort(input, first+1, right); }
ac结果:
后来看大家的题解,发现用堆排序的也比较多的:
//堆排序 public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) { ArrayList<Integer> list = new ArrayList<>(); if(input.length == 0 || input.length < k || k < 0){ return list; } //构建最大堆 for(int len = k/2-1 ; len >= 0 ; len --){ maxHeapSort(input , len , k-1); } //从第k个元素开始 与最大堆里的数比较 int temp = 0; for(int i = k ; i < input.length ; i ++){ if(input[i] < input[0]){ temp = input[0]; input[0] = input[i]; input[i] = temp; maxHeapSort(input , 0 , k-1);//重建 } } for(int i = 0 ; i < k ; ++ i){ list.add(input[i]); } return list; } public void maxHeapSort(int[] input, int pos, int len) { int temp = 0; int child = 0; for(temp = input[pos] ; 2*pos+1<=len ; pos = child){ child = 2*pos+1; if(child < len && input[child] < input[child+1]){ child ++; } if(input[child] > temp){ input[pos] = input[child]; }else{ break; } } input[pos] = temp; }
ac结果:
0 0
- 牛客网刷题之最小的K个数
- 剑指Offer之 - 最小的k个数
- 剑指offer之最小的k个数
- java之最小的k个数
- 【剑指offer】之最小的k个数
- 剑指offer之最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的K个数
- 最小的k个数
- 最小的K个数
- if (Object.ReferenceEquals(str1,str2))
- pandas io tools(使用python处理数据时候经常用到)读csv,TXT
- 认识高斯分布
- JavaScript设计模式都有哪些?
- Bootstrap Table
- 牛客网刷题之最小的K个数
- BZOJ4385 POI2015 Wilcze doły
- Android中logcat的介绍和使用
- 图片延迟加载方案
- Linux Zip Command
- python keras (一个超好用的神经网络框架)的使用以及实例
- You need to use a Theme.AppCompat theme (or descendant) with this activity解决方法
- javascript阻止事件冒泡和浏览器的默认行为
- Linux学习笔记 --- Centos 查看端口被哪个进程被占用