Title Description
Input integer array arr, find the smallest number k. For example, digital input 4,5,1,6,2,7,3,8 eight, the minimum number is four 1,2,3,4.
Thinking
- Hash table, the title given arr.length <10000, arr [i] <10000, the number of times to establish a record for each array Hash number appears, then [0] is output from the Hash, if the Hash [i]> 0 , the output of the cycle until the Hash [i] = 0 or k = 0
- Heap ideas
Code
class Solution {
public:
vector<int> getLeastNumbers(vector<int>& arr, int k) {
vector<int> res;
if(arr.size()==0 || k==0)
return res;
vector<int> Hash(10000);
for(int i = 0;i<arr.size();i++)
{
Hash[arr[i]]++;
}
int count = 0;
while(k>0)
{
while(Hash[count]>0 && k > 0)
{
res.push_back(count);
Hash[count]--;
k--;
}
count++;
}
return res;
}
};
Method Two:
class Solution {
public:
vector<int> getLeastNumbers(vector<int>& arr, int k) {
vector<int> res;
if(k == 0){
return res;
}
priority_queue<int> h;
for(int num : arr){
if(h.size() < k){
h.push(num);
}else{
if(h.top() <= num){
continue;
}else{
h.pop();
h.push(num);
}
}
}
while(!h.empty()){
res.push_back(h.top());
h.pop();
}
return res;
}
};