[每日一题]73:最小的K个数

题目描述

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

代码示例:

#include 
#include 
using namespace std;

class Solution {
	void HeapAdjustDown(vector<int>& arr, int start, int end) {
		int temp = arr[start];
		int i = start * 2 + 1;
		while (i <= end) {
			if (i + 1 <= end && arr[i + 1] < arr[i]) {
				i++;
			}
			if (arr[i] > temp) {
				break;
			}
			arr[start] = arr[i];
			start = i;
			i = start * 2 + 1;
		}
		arr[start] = temp;
	}
public:
	vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
		vector<int> result;
		if (input.size() == 0 || k == 0 || k > input.size()) {
			return result;
		}

		int len = input.size();
		// 初始化堆
		for (int i = len / 2 - 1; i >= 0; i--) {
			HeapAdjustDown(input, i, len - 1);
		}
		for (; k > 0; k--) {
			result.push_back(input[0]);
			int temp = input[len - 1];
			input[len - 1] = input[0];
			input[0] = temp;

			len--;
			//将arr[0...i-1]重新调整为最大堆
			HeapAdjustDown(input, 0, len - 1);
		}
		return result;
	}
};

int main() {
	Solution s;
	int n, k;
	cin >> n >> k;
	vector<int> v, re;
	v.resize(n);
	for (int i = 0; i < n; i++) {
		cin >> v[i];
	}
	re = s.GetLeastNumbers_Solution(v, k);
	for (int i = 0; i < re.size(); i++) {
		cout << re[i] << ',';
	}
	return 0;
}

代码生成图:
[每日一题]73:最小的K个数_第1张图片


如有不同见解,欢迎留言讨论~~

你可能感兴趣的:(牛客网,每日一题)