题目很简单,不做说明:
#include <iostream>
using namespace std;
int array[] = {1, 10, 8, 7, 6, 9, 2, 3, 4, 5};
const int size = sizeof array / sizeof *array;
bool g_Error = false;
int findSecondMax(int *array, int size)
{
if (array == NULL || size < 0)
{
g_Error = true;
return -1;
}
int max1 = 1 << 31;
int max2 = 1 << 31;
for (int i = 0; i < size; i++)
{
if (array[i] > max1)
{
max2 = (max2 > max1) ? max2 : max1;
max1 = array[i];
}
else
{
max2 = (max2 > array[i]) ? max2 : array[i];
}
}
return max2;
}
void main()
{
int result = findSecondMax(array, size);
if (g_Error == true)
{
cout << "wrong input" << endl;
}
else
{
cout << "second max: " << result << endl;
}
}
题目虽然简单,但是有一点得要和面试官沟通,那就是当所有的数字相等的时候,第二大的数取什么,具体可以分为下面两种情形:
1. 只有一个数字
2. 两个或多个数字相等