0
点赞
收藏
分享

微信扫一扫

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

早安地球 2022-02-03 阅读 62
蓝桥杯p2p

题目描述

某次科研调查时得到了 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 条评论