題目描述:
輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4。
時間複雜度O(n)
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> result;
int length = input.size();
if(input.empty() || k<1 || k>length) 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 first, int last){
int i = first;
int j = last;
int key = input[first];
if(first < last){
while(i<j){
while(i<j && key <= input[j]) j--;
if(i < j) input[i++] = input[j];
while(i<j && key >= input[i]) i++;
if(i<j) input[j--] = input[i];
}
input[i] = key;
}
return i;
}
};
時間複雜度O(nlogk)
class Solution
{
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k)
{
int len = input.size();
vector<int> ans;
if(k<1 || k>len)
return ans;
for(int i = 0; i<len; i++)
{
if(ans.size()<k)
{
ans.push_back(input[i]);
if(ans.size()==k)
sort(ans.begin(),ans.end());
}
else
{
if(input[i]<ans[k-1])
{
ans[k-1] = input[i];
if(k>1 && ans[k-1]<ans[k-2])
sort(ans.begin(),ans.end());
}
}
}
return ans;
}
};
如有建議或其他問題,可隨時給我們留言。或者到以下鏈接:
Star/Fork/Push 您的代碼,開源倉庫需要您的貢獻。
請查看Coding 題目網址和收藏Accepted代碼倉庫,進行coding!!!