牛骨文教育服务平台(让学习变的简单)
博文笔记

leetcode--一个for循环找出数组最大和次最大值

创建时间:2016-12-09 投稿人: 浏览次数:2200
//给定一个数组,找出数组中最大值和次最大值。要求在一个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;
}

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。