[Arrays]D. Liang 6.2 Alternative solution to Listing 6.1.c

Description

The solution of Listing 6.1, TestArray.cpp counts the occurrences of the largest number by comparing each number with the largest. So you have to use an array to store all the numbers. Another way to solve the problem is to maintain two variables, max and count. max stores the current max number, and count stores its occurrences. Initially, assign the first number to max and 1 to count. Compare each subsequent number with max. If the number is greater than max, assign it to max and reset count to 1. If the number is equal to max, increment count by 1. Use this approach to rewrite Listing 6.1.

Input

The first line is a positive integer t for the number of test cases.
Each test case contains two lines. The first line is an integer n (0<n<=100). The second line contains n integers.

Output

For each test case, output the largest number and it’s occurrences, seperated by one blank.

Sample Input

2
3
1 2 3
4
2 1 2 1

Sample Output

3 1
2 2
//   Date:2020/4/9
//   Author:xiezhg5
#include <stdio.h>
int main(void)
{
	int i,m,n,a[10000]={0},index=0,cnt=0;   //数组元素个数可能有差异,多试几次就过了随机测试 
	scanf("%d\n",&m);  //一定要读入回车符 
	while(m--)
	{
		cnt=0,index=0;
		scanf("%d",&n);
	    for(i=0;i<n;i++)         //for循环为数组元素下标赋值 
		scanf("%d",&a[i]);
	    for(i=0;i<n;i++)
		if(a[i]>a[index]) //找到最大的数组元素并标记其下标 
			index=i;
		//又一层for循环比较最大元素出现的次数 
		for(i=0;i<n;i++)
		{
			if(a[i]==a[index])
				cnt++;
		}
	    printf("%d %d\n",a[index],cnt);	
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值