Design an algorithm to find the smallest K numbers in an array.
Example 1:
Input: arr = [1,3,5,7,2,4,6,8], k = 4 Output: [1,2,3,4]
0 <= len(arr) <= 100000
0 <= k <= min(100000, len(arr))
水题。给出原理相同但思路相反的两个方法:
唯一不同的是,第二种方法需使用greater
推荐使用方法1,速度较快。
方法1
class Solution {
public:
vector<int> smallestK(vector<int>& arr, int k) {
partial_sort(arr.begin(), arr.begin() + k, arr.end());
vector<int> ans(arr.begin(), arr.begin() + k);
return ans;
}
};
方法2
class Solution {
public:
vector<int> smallestK(vector<int>& arr, int k) {
partial_sort(arr.begin(), arr.begin() + arr.size() - k, arr.end(), greater<int>());
vector<int> ans(arr.begin() + arr.size() - k, arr.end());
return ans;
}
};
LeetCode 17.14 - Smallest K LCCI
原文:https://www.cnblogs.com/ikaroinory/p/14793306.html