zoukankan      html  css  js  c++  java
  • 面试题:最小的K个数

    题目描述:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

    方法1:排序

    方法2:分割

    import java.util.*;
    public class Solution {
        public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
            ArrayList<Integer> result = new ArrayList<>();
            if(input.length < k || input == null || k <= 0){
                return result;
            }
            int start = 0;
            int end = input.length - 1;
            int index = partition(input,start,end);
            while(index != k-1){
                if(index>k-1){
                    end = index - 1;
                    index = partition(input,start,end);
                }else{
                    start = index + 1;
                    index = partition(input,start,end);
                }
            }
            for(int i=0;i<=index;i++){
                result.add(input[i]);
            }
            return result;
        }
        public int partition(int[] input,int start,int end){
            int temp = input[start];
            while(start < end){
                while(start<end&&temp<=input[end]){
                    --end;
                }
                input[start] = input[end];
                while(start<end&&input[start]<temp){
                    ++start;
                }
                input[end] = input[start];
            }
            input[start] = temp;
            return start;
        }
    }

    方法3:堆排序

  • 相关阅读:
    数据库被黑后留下的数据
    cron(CronTrigger)表达式用法
    nodeJS常用的定时执行任务的插件
    css实现隐藏滚动条
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
  • 原文地址:https://www.cnblogs.com/Aaron12/p/9511894.html
Copyright © 2011-2022 走看看