最小的K个数
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
解法一:O(n)牛客超时了,本地调试同乐。
1 class Solution { 2 public: 3 4 void Swap(int &x1,int& x2) 5 { 6 int temp = x1; 7 x1 = x2; 8 x2 = temp; 9 } 10 11 int Partition(vector<int> &input,int start,int end) 12 { 13 int begin = start; 14 int last = end; 15 int key = input[end]; 16 while(begin<last) 17 { 18 while(begin<last && (input[begin]<= key)) 19 begin++; 20 while(begin<last && input[last]>=key) 21 last--; 22 Swap(input[begin],input[end]); 23 } 24 Swap(input[begin],input[end]); 25 return begin; 26 } 27 28 vector<int> GetLeastNumbers_Solution(vector<int> &input, int k) { 29 vector<int> result; 30 if(input.size()==0) 31 return result; 32 int start = 0; 33 int end = input.size() - 1; 34 int index = Partition(input,start,end); 35 while(index!=k-1) 36 { 37 if(index>k-1) 38 { 39 end = index-1; 40 index = Partition(input,start,end); 41 } 42 else 43 { 44 start = index + 1; 45 index = Partition(input,start,end); 46 } 47 } 48 for(int i= 0;i<k;i++) 49 { 50 result.push_back(input[i]); 51 } 52 return result; 53 } 54 };
解法二:
浙公网安备 33010602011771号