面试中遇到的问题,挺有意思的记录一下。
C++版本
// 快排变形.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include <vector> using namespace std; int partion(vector<int>& nums,int left, int right) { int key = nums[left]; while (left < right) { while (left < right && nums[right] >= key) right--; nums[left] = nums[right]; while (left < right && nums[left] <= key) left++; nums[right] = nums[left]; } nums[left] = key; return left; } int topK(vector<int>& nums, int low, int high, int k) { if (low == high) return nums[low]; int pos = partion(nums, low, high); int len = high - pos + 1; if (len == k) return nums[pos]; else if (len > k) return topK(nums, pos+1, high, k); else return topK(nums, low, pos -1, k-len); } int main() { vector<int> nums = { 12,52,1,59,46,49,65,58,15,34,28,9,5 }; int n = nums.size(); cout << topK(nums, 0, n - 1, 3); }