找出数组中最小的 K 个数

来源:互联网 发布:discuz nt 4.0 源码 编辑:程序博客网 时间:2024/06/10 18:24

给定一个长度为 n 的数组,要求输出数组中最小的 K 个数(k<n)。

思路:

最简单的思路是将数组进行排序,由小到大排序,则数组最前面的 K 个既我们要求的。

但是这样的时间复杂度为 nlongn,在排序上是最优了,但是在这道题不是。

我们可以利用 快速排序的原理,Partition 函数。将比初始数字 temp 小的数放在左边,比 temp 放在右边。

如果 temp 刚好是第 k 个数字,那么,temp 前面(包括temp)就是所求。


package com.hunter.Offer_Example;import java.util.Scanner;/** * 给定一个数组,找出数组中最小 K 个数字 * 例如给定数组 1 20 11 12 2 9 10 6 8 18 *最小的3个数字为: 1  2  6 * @author luzi * */public class findTheKMinNum {public static void main(String[] args) {// TODO Auto-generated method stubScanner scan = new Scanner(System.in);while(scan.hasNext()){int k = scan.nextInt();int n = scan.nextInt();int[] arr = new int[n];for(int i = 0; i < n; i++){arr[i] = scan.nextInt();}int index = Partition(arr,n,0,n-1);while(index != k-1){if(index > k - 1){index = Partition(arr,n,0,index - 1);}elseindex = Partition(arr,n,index + 1,n-1);}for(int i =0; i < k; i++)System.out.println(arr[i]);}}public static int Partition(int[] arr,int n,int start,int end){int temp = arr[start];while(start < end){while(start < end && arr[end] >= temp)end--;if(start < end)arr[start++] = arr[end];while(start < end && arr[start] < temp)start++;if(start < end)arr[end--] = arr[start];}arr[start] = temp;return start;}}


实际运行: