leetcode--一个for循环找出数组最大和次最大值
//给定一个数组,找出数组中最大值和次最大值。要求在一个for循环里实现
#include "stdafx.h"
#include<iostream>
using namespace std;
void select_max(const int*a, int size, int&nMax, int& nSecondMax)
{
nMax = a[0];
nSecondMax = a[0];
for (int i = 0; i < size; i++)
{
if (nMax < a[i])
{
nSecondMax = nMax;//注意前后顺序,如果是第三个最大值,则在最上边,然后到次最大,。。。
nMax = a[i];
}
else if (nSecondMax < a[i])
{
nSecondMax = a[i];
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[] = { 1, 5, 48, 46,1,4,7,5};
int nMax, nSecondMax;
select_max(a, sizeof(a) / sizeof(int), nMax, nSecondMax); //每个int占4个字节,数组没有以 结束,因此sizeof(a) / sizeof(int)可以表示数组中的元素个数
cout << nMax << endl;
cout << nSecondMax << endl;
cout << sizeof(a) << endl;
return 0;
}
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了
