时间限制: 1秒 空间限制: 32768K
本题知识点: 数组 高级算法
题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
思路分析
先排序,再返回前k个数,个人喜欢用归并排序
C#语言
public void MergeSort(int[] nums, int left, int right)
{
if (left < right)
{
int middle = (left + right) / 2;
MergeSort(nums, left, middle);
MergeSort(nums, middle + 1, right);
int[] array = new int[right - left + 1];
int il = left, ir = middle + 1, index = 0;
while (il <= middle && ir <= right) array[index++] = nums[il] < nums[ir] ? nums[il++] : nums[ir++];
while (il <= middle) array[index++] = nums[il++];
while (ir <= right) array[index++] = nums[ir++];
for (index = 0, il = left; il <= right; ) nums[il++] = array[index++];
}
}
public List<int> GetLeastNumbers_Solution(int[] input, int k)
{
List<int> nums = new List<int>();
if (k == 0 || k > input.Length) return nums;
MergeSort(input, 0, input.Length - 1);
for (int i = 0; i < k; ++i)
{
nums.Add(input[i]);
}
return nums;
}