剑指offer面试题30:最小的K个数

来源:互联网 发布:php 输出等边三角形 编辑:程序博客网 时间:2024/05/21 15:02

题目:输入n个整数,找出其中最小的k个数。
思路:与29题类似。

#include <iostream>#include <vector>using namespace std;int Partition(vector<int> &num, int length, int begin, int end) {  if (num.empty() || length <= 0 || begin < 0 || end >= length)    return -1;  int index = begin;  int small = begin - 1;  while (index < end) {    if (num[index] < num[end]) {      ++small;      int temp = num[index];      num[index] = num[small];      num[small] = temp;    }    ++index;  }  ++small;  int temp = num[small];  num[small] = num[end];  num[end] = temp;  return small;}void SmallestK(vector<int> &num, int length, int k) {  if (num.empty() || length <= 0)    return;  int begin = 0;  int end = length - 1;  int index = Partition(num, length, begin, end);  while (index != k - 1) {    if (index > k - 1) {      end = index - 1;      index = Partition(num, length, begin, end);    } else {      begin = index + 1;      index = Partition(num, length, begin, end);    }  }  for (int i = 0; i < k; i++) {    cout << num[i] << " ";  }  cout << endl;}int main() {  vector<int> num;  int k;  cin >> k;  int a;  while (cin >> a) {    num.push_back(a);  }  a = num.size();  SmallestK(num, a, k);  for (auto c : num)    cout << c << " ";  cout << endl;  return 0;}
0 0
原创粉丝点击