方法一,先将数组排序,然后得到前k个数即可。
class Solution {public:vector<int> getLeastNumbers(vector<int>& arr, int k) {sort(arr.begin(), arr.end());vector<int> res;for (int i=0;i<k;++i) {res.push_back(arr[i]);}return res;}};
leedcode通过:
执行用时:20 ms, 在所有 C++ 提交中击败了91.48% 的用户内存消耗:18.6 MB, 在所有 C++ 提交中击败了47.90% 的用户
