题解 | #最小的K个数#

最小的K个数

https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf

#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param input int整型vector 
     * @param k int整型 
     * @return int整型vector
     */
    vector<int> GetLeastNumbers_Solution(vector<int>& input, int k) {
        // write code here
        int index;
        vector<int> temp = input;
        vector<int> res;
	  	// 排除特殊情况
        if (k == 0) {
            return res;
        }
	  	// 输出数组中有k个元素,时间复杂度o(k)
        for (int i = 0; i < k; i++) {
		  	// 寻找数组中的最小值,时间复杂度o(n)
            int minc = 1e9;
            for (int j = 0; j < temp.size(); j++) {
                if (temp[j] < minc) {
                    minc = temp[j];
                    index = j;
                }
            }
		  	// 加入输出结果中
            res.push_back(minc);
		  	// 将最小值从temp数组中去掉,在新数组中继续找最小值
            for (int k = index + 1; k < temp.size(); k++) {
                temp[k - 1] = temp[k];
            }
            temp.reserve(temp.size() - 1);
        }
        return res;
    }
};

全部评论

相关推荐

自由水:这HR已经很好了,多的是已读不回和不读了
点赞 评论 收藏
分享
那一天的Java_Java起来:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务