1.这个通过partition实现topk,时间复杂度是o(logn*logn),也就是0(n),但需要修改原数组的顺序
下面这个代码本身有一些错误,并且throw excption会在牛客上报错
class Solution { public: vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { vector<int> result; int length = input.size(); if(input.empty() || length <= 0 || k <= 0 || length < k) return result; int start = 0; int end = length - 1; int index = partition(input,length,start,end); while(index != k-1){ if(index > k-1){ end = index-1; index = partition(input,length,start,end); } else{ start = index + 1; index = partition(input,length,start,end); } } for(int i = 0;i <= index;i++) result.push_back(input[i]); return result; } int partition(vector<int> &input,int length,int start,int end){ if(input.empty() || length <= 0 || start < 0 || end >= length) throw new exception("Invalid Parameters"); int small = -1; for(int i = start;i <= end;i++){ if(input[i] <= input[end]){ start++; if(start != i) swap(&input[start],&input[i]); } } small++; swap(&input[small],&input[end]); return small; } };
正确代码
class Solution { public: vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { vector<int> result; int length = input.size(); if(input.empty() || length <= 0 || k <= 0 || length < k) return result; int start = 0; int end = length - 1; int index = partition(input,start,end); while(index != k-1){ if(index > k-1){ end = index - 1; index = partition(input,start,end); } else{ start = index + 1; index = partition(input,start,end); } } for(int i = 0;i < k;i++) result.push_back(input[i]); return result; } int partition(vector<int> &input,int start,int end){ int small = start - 1; for(int i = start;i < end;i++){ if(input[i] < input[end]){ small++; if(small != i) swap(input,small,i); } } small++; swap(input,small,end); return small; } void swap(vector<int>& input,int a,int b){ int tmp = input[a]; input[a] = input[b]; input[b] = tmp; } };
2.用大根堆的做法的时间复杂度是o(nlogk)