如题:1.从一组数中找到第二大的数,假设这组数无序,存储在数组中
#include "stdafx.h"
#include<iostream>
using namespace std;
int findTheSecondLargeNum(int arr[],int length)
{
int maxValue = arr[0];
int secondValue= arr[0];
bool flag = false;
if (length < 2)
{
return -1;
}
for (int i = 1; i < length; ++i)
{
if ((arr[i] < maxValue) && (flag == false))//consider the reverse order situation
{
secondValue = arr[i];
flag = true;
}
else if((arr[i] > secondValue)&&(arr[i] < maxValue))
{
secondValue = arr[i];
}
else if (arr[i] > maxValue)
{
secondValue = maxValue;
maxValue = arr[i];
flag = true;
}
}
if(flag == false)
{
cout<<"the array does not fit "<<endl;
return -1;
}
return secondValue;
}
void main()
{
int arr[] = {6,5,4,3,2,1};
int length = sizeof(arr)/sizeof(int);
int result;
result = findTheSecondLargeNum(arr,length);
cout<<"the second large number is "<<result<<endl;
system("pause")
输出:the second large number is 5输出:the second large number is 5输出:the second large number is 5输出:the second large number is 5
输出:the second large number is 5
如题:2.从一组数中找到不小于第二大数的数字的个数,假设这组数无序,存储在数组中。
#include "stdafx.h"
#include<iostream>
using namespace std;
int findTheSecondLargeNum(int arr[],int length)
{
int maxValue = arr[0];
int secondValue= arr[0];
int maxCount = 1;
int secondCount = 0;
bool flag = false;
if (length < 2)
{
cout<<"there isn't the second larger number!";
return -1;
}
for (int i = 1; i < length; ++i)
{
if ((arr[i] < maxValue) && (flag == false))
{
secondValue = arr[i];
flag = true;
secondCount = 1;
}
else if((arr[i] >= secondValue)&&(arr[i] < maxValue))
{
secondValue = arr[i];
++secondCount;
}
else if(arr[i] == maxValue)
{
++maxCount;
}
else if (arr[i] > maxValue)
{
secondValue = maxValue;
maxValue = arr[i];
secondCount = maxCount;
maxCount = 1;
flag = true;
}
}
if(flag == false)
{
cout<<"the array does not fit "<<endl;
return -1;
}
return maxCount + secondCount;
}
void main()
{
int arr[] = {-1,2,8,3,5,8,4,6,9,7,5,1,8,2,6};
int length = sizeof(arr)/sizeof(int);
int result;
result = findTheSecondLargeNum(arr,length);
cout<<"There are "<<result<<" numbers larger than the second larger number"<<endl;
system("pause");
}
输出: There are 4 numbers larger than the second larger number