题目:输入N个整数,找出其中最小的k个整数。例如输入 4,5,1,6,2,7,3,8,输入k=4,则输出最小的四个数是1,2,3,4 算法分析: 算法1.O(n)的算法,修改输入的数组 可以基于get

来源:互联网 发布:mac装了win10怎么切换 编辑:程序博客网 时间:2024/06/07 21:11
题目:输入N个整数,找出其中最小的k个整数。例如输入 4,5,1,6,2,7,3,8,输入k=4,则输出最小的四个数是1,2,3,4
算法分析:
算法1.O(n)的算法,修改输入的数组
可以基于getMiddle函数来解决此问题。如果基于数组的第k个数字来调整,使得第k个数字小的所有数字都位于数组的左边,比第k个数字大的所有数字都位于数组的右边。这样调整后,位于数组左边的k个数字就是最小的k个数字。

算法2.O(nlogk)的算法,适合处理海量数据

此种算法需要使用Java中的TreeSet排序并去除重复元素,利用ArrayList存储并输出。
TreeSet原理:TreeSet在存储对象的时候,可以排序,但是需要制定排序的算法。其中的Integer和String都能实现默认的排序顺序。在使用TreeSet存储对象的时候,add()方法内部就会自动调用compareTo()方法进行比较,根据比较结果使用二叉树的形式进行存储。
TreeSet是一个有序集合,TreeSet中的元素将按照升序排列,缺省是按照自然排序进行排列,意味着TreeSet中的元素要实现Comparable接口。或者有一个自定义的比较器。
我们可以在构造TreeSet对象时,传递实现Comparator接口的比较器对象。
TreeSet事例代码:
import java.util.Iterator;import java.util.*;public class TreeSetTest {    public static void main(String[] args) {        Set ts = new TreeSet();        ts.add("abc");        ts.add("xyz");        ts.add("rst");        Iterator it = ts.iterator();        while (it.hasNext()) {            System.out.println(it.next());        }    }}
输出结果:
abc
rst
xyz
来源: http://www.cnblogs.com/ningvsban/archive/2013/05/06/3062535.html
算法3.冒泡排序
采用冒泡排序的思想,最外层循环k次就可以了,也就是说不用全部排列,只调出符合提议的k个就可以了。


算法1源程序:
[java] view plain copy
  1. /**************************************************************       
  2. * Copyright (c) 2016,  
  3. * All rights reserved.                    
  4. * 版 本 号:v1.0                    
  5. * 题目描述:最小的k个数。 
  6. *              输入N个整数,找出其中最小的k个整数。例如输入 4,5,1,6,2,7,3,8,输入k=4,则输出最小的四个数是1,2,3,4 
  7.  
  8. * 输入描述:请输入一个数组,以空格隔开: 
  9. *           1 4 6 8 3 5 9 0 
  10. *           请输入k的值: 
  11. *           4 
  12. * 程序输出: 最小4个数是:0, 1, 3, 4 
  13. * 问题分析: 无 
  14. * 算法描述:算法1.可以基于getMiddle函数来解决此问题。如果基于数组的第k个数字来调整, 
  15. *           使得第k个数字小的所有数字都位于数组的左边,比第k个数字大的所有数字都位于数组的右边。 
  16. *           这样调整后,位于数组左边的k个数字就是最小的k个数字。 
  17. * 完成日期:2016-09-18 
  18. ***************************************************************/  
  19.   
  20. package org.marsguo.offerproject30;  
  21.   
  22. import java.util.Scanner;  
  23.   
  24. class FindTheLeastNumber{  
  25.     public void leastNumberFun(int[] inputarray,int k){  
  26.         if(inputarray == null || k > inputarray.length ||   
  27.                 inputarray.length <= 0 || k <= 0)  
  28.             return;  
  29.           
  30.         int n = inputarray.length;  
  31.         int start = 0;  
  32.         int end = n -1;  
  33.         int index = getMiddle(inputarray,start,end);  
  34.         while(index != k - 1){                          //利用getMiddle函数进行快速排序,找出K之前的所有数  
  35.             if(index > k - 1){  
  36.                 end = index - 1;  
  37.                 index = getMiddle(inputarray, start, end);  
  38.             }  
  39.             else{  
  40.                 start = index + 1;  
  41.                 index = getMiddle(inputarray, start, end);  
  42.             }  
  43.         }  
  44.         int[] outputarray = new int[k];  
  45.         for(int i = 0; i < k; ++i){  
  46.             outputarray[i] = inputarray[i];  
  47.               
  48.         }  
  49.             System.out.println("最小的" + k + "个数是:");  
  50.             for(int i = 0; i < k; ++i){  
  51.                 System.out.print(outputarray[i] + ",");  
  52.                   
  53.             }  
  54.     }  
  55.       
  56.     public int getMiddle(int[] sortArray,int low,int high){  
  57.         int key = sortArray[low];  
  58.         while(low<high){  
  59.             while(low <high && sortArray[high] >= key){       //就因为缺少一个“=”,就会导致整个循环无法退出  
  60.                 high--;  
  61.             }  
  62.             sortArray[low] = sortArray[high];  
  63.             while(low < high && sortArray[low] < key){  
  64.                 low++;  
  65.             }  
  66.             sortArray[high] = sortArray[low];  
  67.         }  
  68.         sortArray[low] = key;  
  69.         return low;  
  70.     }  
  71. }  
  72.   
  73. public class GetLeastNumber {  
  74.     public static void main(String[] args){  
  75.         Scanner scanner = new Scanner(System.in);  
  76.         System.out.println("请输入一个数组,以空格隔开:");  
  77.         String str = scanner.nextLine();  
  78.         System.out.println("请输入K的值:");  
  79.         int k = scanner.nextInt();  
  80.         scanner.close();                        //scanner使用后需要close,否则报警告。  
  81.         String[] temp = str.split(" ");  
  82.         int[] array = new int[temp.length];  
  83.         for(int i = 0; i<temp.length; i++){  
  84.             array[i] = Integer.parseInt(temp[i]);  
  85.         }  
  86.           
  87.         FindTheLeastNumber findnum = new FindTheLeastNumber();  
  88.         findnum.leastNumberFun(array, k);  
  89.           
  90.     }  
  91. }  

算法2源程序:
[java] view plain copy
  1. /**************************************************************       
  2. * Copyright (c) 2016,  
  3. * All rights reserved.                    
  4. * 版 本 号:v1.0                    
  5. * 题目描述:最小的k个数。 
  6. *              输入N个整数,找出其中最小的k个整数。例如输入 4,5,1,6,2,7,3,8,输入k=4,则输出最小的四个数是1,2,3,4 
  7. * 输入描述:请输入一个数组,以空格隔开: 
  8. *           1 4 6 8 3 5 9 0 
  9. *           请输入k的值: 
  10. *           4 
  11. * 程序输出: 最小4个数是:0, 1, 3, 4 
  12. * 问题分析: 1. GetLeastNumbers_Solution(int[] input,int k)函数必须声明为static, 
  13. *           因为在同一个类中,main函数要引用这个函数,但main函数是static,所以 
  14. *           这个函数也必须声明为static 
  15. * 算法描述:算法2.此种算法需要使用Java中的TreeSet排序并去除重复元素,利用ArrayList存储并输出。 
  16. *           TreeSet原理:TreeSet在存储对象的时候,可以排序,但是需要制定排序的算法。 
  17. *           其中的Integer和String都能实现默认的排序顺序。在使用TreeSet存储对象的时候, 
  18. *           add()方法内部就会自动调用compareTo()方法进行比较,根据比较结果使用二叉树的形式进行存储。 
  19. * 完成日期:2016-09-18 
  20. ***************************************************************/  
  21.   
  22. package org.marsguo.offerproject30;  
  23.   
  24. import java.util.*;  
  25. /*利用TreeSet排序并去除重复元素,利用ArrayList存储并输出*/  
  26. public class TreeSetSolution {  
  27.     /*此函数必须声明为static,因为在同一个类中,main函数要引用这个函数,但main函数是static,所以 
  28.     这个函数也必须声明为static*/  
  29.     public  static ArrayList<Integer> GetLeastNumbers_Solution(int[] input,int k){  
  30.         ArrayList<Integer> list = new ArrayList<Integer>();  
  31.         ArrayList<Integer> list2 = new ArrayList<Integer>();  
  32.         if(input == null || input.length == 0 || k ==0 || k > input.length)  
  33.             return list;  
  34.         TreeSet<Integer> set = new TreeSet<Integer>();  
  35.         for(int i = 0 ; i < input.length; i++){  
  36.             set.add(input[i]);  
  37.         }  
  38.         /*Set类的iterator()返回一个实例,这个实例是Iterator的实现类。此句相当于向上转型 
  39.         Set<Integer> set = new HashSet<>(); 
  40.         Iterator<Integer> it = set.iterator();*/  
  41.           
  42.         Iterator<Integer> it = set.iterator();  
  43.         while(it.hasNext()){  
  44.             int x = it.next();  
  45.             list.add(x);  
  46.         }  
  47.         for(int i = 0; i < k; i++){          //将排序后的前k个数取出,放入list2集合中  
  48.             list2.add(list.get(i));  
  49.         }  
  50.         return list2;                       //返回的就是排序后需要输出的k个数  
  51.     }  
  52.       
  53.     public static void main(String[] args){  
  54.         Scanner scanner = new Scanner(System.in);  
  55.         System.out.println("请输入一个数组,以空格隔开:");  
  56.         String str = scanner.nextLine();  
  57.         System.out.println("请输入K的值:");  
  58.         int k = scanner.nextInt();  
  59.         scanner.close();                        //scanner使用后需要close,否则报警告。  
  60.         String[] temp = str.split(" ");  
  61.         int[] array = new int[temp.length];  
  62.         for(int i = 0; i<temp.length; i++){  
  63.             array[i] = Integer.parseInt(temp[i]);  
  64.         }  
  65.           
  66.         //GetLeastNumbet_Solution函数必须声明为static才能引用  
  67.         System.out.println("最小" + k +"个数是:" + GetLeastNumbers_Solution(array,k));  
  68.     }  
  69. }  

算法3源程序:
[java] view plain copy
  1. /**************************************************************       
  2. * Copyright (c) 2016,  
  3. * All rights reserved.                    
  4. * 版 本 号:v1.0                    
  5. * 题目描述:最小的k个数。 
  6. *              输入N个整数,找出其中最小的k个整数。例如输入 4,5,1,6,2,7,3,8,输入k=4,则输出最小的四个数是1,2,3,4 
  7. * 输入描述:请输入一个数组,以空格隔开: 
  8. *           1 4 6 8 3 5 9 0 
  9. *           请输入k的值: 
  10. *           4 
  11. * 程序输出: 最小4个数是:0, 1, 3, 4 
  12. * 问题分析: 无 
  13. * 算法描述:算法3.采用冒泡排序的思想,最外层循环k次就可以了,也就是说不用全部排列,只调出符合提议的k个就可以了。 
  14. * 完成日期:2016-09-18 
  15. ***************************************************************/  
  16.   
  17. package org.marsguo.offerproject30;  
  18.   
  19. import java.util.ArrayList;  
  20. import java.util.Scanner;  
  21.   
  22. class Solution{  
  23.     public ArrayList<Integer> GetLeastNumbers_Solution(int[] input,int k){  
  24.          ArrayList<Integer> al = new ArrayList<Integer>();  
  25.         if (k > input.length) {  
  26.             return al;  
  27.         }  
  28.         for (int i = 0; i < k; i++) {  
  29.             for (int j = 0; j < input.length - i - 1; j++) {  
  30.                 if (input[j] < input[j + 1]) {  
  31.                     int temp = input[j];  
  32.                     input[j] = input[j + 1];  
  33.                     input[j + 1] = temp;  
  34.                 }  
  35.             }  
  36.             al.add(input[input.length - i - 1]);  
  37.         }  
  38.         return al;  
  39.     }  
  40. }  
  41. public class PopSortSolution {  
  42.     public static void main(String[] args){  
  43.         Scanner scanner = new Scanner(System.in);  
  44.         System.out.println("请输入一个数组,以空格隔开:");  
  45.         String str = scanner.nextLine();  
  46.         System.out.println("请输入K的值:");  
  47.         int k = scanner.nextInt();  
  48.         scanner.close();                        //scanner使用后需要close,否则报警告。  
  49.         String[] temp = str.split(" ");  
  50.         int[] array = new int[temp.length];  
  51.         for(int i = 0; i<temp.length; i++){  
  52.             array[i] = Integer.parseInt(temp[i]);  
  53.         }  
  54.         Solution solution = new Solution();  
  55.           
  56.         //GetLeastNumbet_Solution函数必须声明为static才能引用  
  57.         System.out.println("最小" + k +"个数是:" +solution.GetLeastNumbers_Solution(array, k));  
  58.     }  
  59. }  
阅读全文
0 0
原创粉丝点击