Q:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
T:
注意空的情况和k过大的情况。
1.直接排序输入。

    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> result;
        if (input.empty())
            return result;
        sort(input.begin(), input.end(), [](const int &a, const int &b) { return a < b; });
        if (k > input.size())
            return result;
        for (int i = 0; i < k; i++)
            result.push_back(input[i]);
        return result;
    }

2.其他排序方法看:https://www.cnblogs.com/xym4869/p/8666860.html
3.全部放入PriorityQueue(默认小根堆),然后pop k次。

相关文章:

  • 2021-08-08
  • 2021-06-10
  • 2022-12-23
  • 2022-02-25
  • 2021-08-08
  • 2021-04-21
  • 2021-07-17
猜你喜欢
  • 2021-08-26
  • 2022-01-27
  • 2022-12-23
  • 2019-11-29
  • 2022-12-23
  • 2021-07-31
  • 2021-07-20
相关资源
相似解决方案