C/C++编程题刷题:最小非零元素

最小非零元素

【题目描述】Q哥给了小Q一个长度为n正整数序列ai。

Q哥要求小Q重复以下操作步骤k轮:

1、发现最小的非零元素x。

2、打印x。

3、将序列中所有非零元素减x。

小Q把这个艰巨的任务交给了你,希望你能帮帮他。 

输入描述

输入包括两行。

第一行包括两个正整数n和k(1<=n,k<=105)。

第二行包括n个正整数ai(1<=ai<=109)。 

输出描述

输出k行,即每轮中的最小非零整数(如果到某轮所有元素都是0,打印0即可)。

示例1

输入

7 5

5 8 10 3 6 10 8

输出

3

2

1

2

2

#include <iostream>
#include <string>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main() {
	int n, k;
	cin >> n >> k;
	vector<int> nums;
	while (n--) {
		int x;
		cin >> x;
		nums.push_back(x);
	}
	sort(nums.begin(),nums.end());
	
	while (k--) 
	{
		while (nums.size() && nums[0] <= 0) 
		{
			nums.erase(nums.begin());
		}
		if (nums.empty()) {
			cout << "0" << endl; 
		}
		else 
		{
			int x = nums[0];
			cout << x << endl;
			nums.erase(nums.begin());
			for (int i = 0; i < nums.size(); i++) {
				nums[i] -= x;
			}
			
		}
	}
	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值