zoukankan      html  css  js  c++  java
  • 剑指offer--最小的k个数

    /**
     * 输入n个整数,找出其中最小的K个数。
     * 例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
     */
    package javabasic.nowcoder;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.PriorityQueue;
    /*
     * 思路一:
     * 用最大堆保存这k个数,每次只和堆顶比,如果比堆顶小,删除堆顶,新数入堆。
     */
    public class Main34 {
    
    	public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
    		ArrayList<Integer> arr = new ArrayList<Integer>();
            if(k<=0||k>input.length) {
            	return arr;
            }
            PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k,new Comparator<Integer>() {
    
    			@Override
    			public int compare(Integer o1, Integer o2) {
    				return o2.compareTo(o1);
    			}
    		});
            
            for(int i=0;i<input.length;i++) {
            	if(maxHeap.size()!=k) {
            		maxHeap.offer(input[i]);
            	}else if(maxHeap.peek()>input[i]) {
            		Integer poll = maxHeap.poll();
            		poll=null;
            		maxHeap.offer(input[i]);
            	}
            }
            for(Integer num : maxHeap) {
            	arr.add(num);
            }
    		return arr;
        }
    	
    	public ArrayList<Integer> GetLeastNumbers_SolutionII(int [] input, int k) {
    		ArrayList<Integer> arr = new ArrayList<Integer>();
            if(input==null||k<=0||k>input.length) {
            	return arr;
            }
    		Arrays.sort(input);
            for(int i=0;i<k;i++) {
            	arr.add(input[i]);
            }
    		return arr;
        }
    	public static void main(String[] args) {
    		int[] res = {4,5,1,6,2,7,3,8};
    		ArrayList<Integer> getLeastNumbers_Solution = new Main34().GetLeastNumbers_Solution(res,4);
    		System.out.println(getLeastNumbers_Solution);
    	}
    }
    

      

  • 相关阅读:
    编译安装Nginx和php搭建KodExplorer网盘
    mysql二进制安装及基础操作
    Apache环境下搭建KodExplorer网盘
    编译安装Apache httpd和php搭建KodExplorer网盘
    KodExplorer介绍
    Nginx反向代理、负载均衡及日志
    Nginx include和Nginx指令的使用
    Nginx auto_index和auth_basic
    [译]在 64bit 环境中执行32 bit的SSIS包
    [译]SSIS 通过环境变量配置数据源连接参数
  • 原文地址:https://www.cnblogs.com/zhaohuan1996/p/9059280.html
Copyright © 2011-2022 走看看