最小的K个数 (最小堆)

来源:互联网 发布:华东师范继续教育网络 编辑:程序博客网 时间:2024/06/03 14:46

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

//冒泡排序,時間复杂度using System.Collections.Generic;class Solution{     public List<int> GetLeastNumbers_Solution(int[] input, int k)        {            // write code here            List<int> list = new List<int>();         if(input.Length<k)         {             return list;         }            for (int i = 0; i < input.Length; i++)            {                for (int j = i+1; j < input.Length-1; j++)                {                    if (input[i]>input[j])                    {                        int temp = input[i];                        input[i] = input[j];                        input[j] = temp;                    }                }            }            for (int i = 0; i < k; i++)            {                list.Add(input[i]);            }            return list;        }}
原创粉丝点击