华为机试题——HJ58 输入n个整数,输出其中最小的k个

描述

输入n个整数,找出其中最小的k个整数并按升序输出

本题有多组输入样例
 

数据范围:1 \le n \le 1000 \1≤n≤1000  ,输入的整数满足 1 \le val \le 10000 \1≤val≤10000 

输入描述:

第一行输入两个整数n和k
第二行输入一个整数数组

输出描述:

从小到大输出最小的k个整数,用空格分开。

示例1

输入:

5 2
1 3 5 7 2

复制输出:

1 2
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <string.h>
#include <malloc.h>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <set>
#include <unordered_set>
#include <map>

void print(int arr[], int n)
{
    std::cout << "n = " << n << std::endl;
    for(int i = 0; i < n; ++i)
    {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}
void print(std::multiset<int> set)
{
    std::set<int>::iterator iter = set.begin();
    while(iter != set.end())
    {
        std::cout << *iter++ << " ";
    }
    std::cout << std::endl;
}

int main()
{
    int n;
    std::cin >> n;
    int len = n;
    int k;
    std::cin >> k;
    int arr[n];
    int i = 0;
    while(n-- > 0)
    {
        std::cin >> arr[i++];
    }
    // print(arr, len);

    //先排序,然后输出前k个元素
    std::multiset<int> setElement;
    for(int i = 0; i < len; ++i)
    {
        setElement.insert(arr[i]);
    }
    // print(setElement);

    std::multiset<int>::iterator iter = setElement.begin();
    for(int i = 0; i < k; ++i)
    {
        std::cout << *iter++ << " ";
    }
    std::cout << std::endl;

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值