Club 1204 众数问题

问题描述:
给定含有n个元素的多重集合S,每个元素在S中出现的次数称为该元素的重数。多重集S中重数最大的元素称为众数。
例如,S={1,2,2,2,3,5}。多重集S的众数是2,其重数为3。
编程任务:
对于给定的由n 个自然数组成的多重集S,编程计算S 的众数及其重数。

输入描述

第1行多重集S中元素个数n(n<=50000);接下来的n 行中,每行有一个自然数。

输出描述

输出文件有2 行,第1 行给出众数,第2 行是重数。(如果有多个众数,只输出最小的)

解题思路:

利用数组,其下标作为输入数据,其值作为这个数据的重复数量,代码如下

void write_data(unsigned int *p, unsigned int n)
{
	unsigned int a(0);
	while (n--){
		std::cin >> a;
		p[a] ++;
	}
}

声明一个变量a,输入值赋值给a,将数组中第a个元素值+1

数据输入完成后,计算结果并输出

void proc_data(unsigned int *p, unsigned int n)
{
	unsigned int ZongShu(0), ChongShu(0), i(0);
	while (i<n){
		if (ChongShu < p[i]){
			ChongShu = p[i];
			ZongShu = i;
		}
		i++;
	}
	std::cout << ZongShu << std::endl;
	std::cout << ChongShu << std::endl;
}

主函数:

int main(void)
{
	unsigned int NUM;
	std::cin >> NUM;
	unsigned int *p = new unsigned int[100000];
	for (int i(0); i < 100000; i++)p[i] = 0;
	
	write_data(p,NUM);
	proc_data(p, 100000);

	delete[] p;
	system("pause");
	return 0;
}

用到动态创建数组 new

function operator new[]

Allocate storage space for array

<类型>    <指针变量>   =   new   <类型>   [<数组长度>]

// operator new[] example
#include <iostream>     // std::cout
#include <new>          // ::operator new[]

struct MyClass {
  int data;
  MyClass() {std::cout << '*';}  // print an asterisk for each construction
};

int main () {
  std::cout << "constructions (1): ";
  // allocates and constructs five objects:
  MyClass * p1 = new MyClass[5];
  std::cout << '\n';

  std::cout << "constructions (2): ";
  // allocates and constructs five objects (nothrow):
  MyClass * p2 = new (std::nothrow) MyClass[5];
  std::cout << '\n';

  delete[] p2;
  delete[] p1;

  return 0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值