统计数字(蓝桥杯题库535)

题目描述

某次科研调查时得到了 n 个自然数,每个数均不超过 1.5*10^9。已知不相同的数不超过 10^4个,现在需要统计这些自然数各自出现的次数,并按照自然数从小到大的顺序输出统计结果。

输入描述

第 1 行是整数 n,表示自然数的个数。

第 2 ~ n+1行每行一个自然数。

其中,1≤n≤2×10^5,每个数均不超过1.5*10^9。

输出描述

输出 m 行( m 为 n 个自然数中不相同数的个数),按照自然数从小到大的顺序输出。每行输出两个整数,分别是自然数和该数出现的次数,其间用一个空格隔开。

输入输出样例

示例 1

输入

8
2
4
2
4
5
100
2
100

输出

2 3
4 2
5 1
100 2

 

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

const int n = 200100;
int N, num, mmax;
int a[n];

 
int main() {
	cin >> N;
	for (int i = 0; i < N; i++) {
		cin >> num;
		if (i == 0) mmax = num;
		else {
			mmax = max(mmax, num);
		}
		a[num]++;
	}
	
	for (int i = 0; i <= mmax; i++) {
		if (a[i] != 0) {
			cout << i << " " << a[i] << endl;
		}
	}
	
	return 0;
}

以上方法是不行的,空间复杂度过大

应采取以下方法,直接遍历即可,时间复杂度为O(n)。

#include <bits/stdc++.h>
using namespace std;

const int N = 200010;
int a[N];

int main() {
	int n; cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}
	sort(a, a+n);
	
	int k = a[0], cnt = 1;
	for (int i = 1; i < n; i++) {
		if (a[i] != k) {
			cout << k << " " << cnt << endl;
			k = a[i];
			cnt = 1;
		} else {
			cnt++;
		}
	}
	cout << k << " " << cnt << endl;
	
	return 0;
}











  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值