给定一个数组,寻找次大的数,你会如何实现?
代码
internal static int FindSecondMaximum(int[] input)
{
if (input &#61;&#61; null || input.Length < 2)
{
throw new InvalidOperationException("the input paramter is invalid, please check your input");
}
int max1 &#61; input[0], max2 &#61; input[1];
Swap(ref max1, ref max2);
for (int i &#61; 2; i < input.Length; i&#43;&#43;)
{
if (input[i] > max2)
{
max2 &#61; input[i];
Swap(ref max1, ref max2);
}
}
//if (max1 &#61;&#61; max2)
//{
// throw new InvalidOperationException("All the given values are same");
//}
return max2;
}
private static void Swap(ref int max1, ref int max2)
{
if (max1 < max2)
{
int temp &#61; max1;
max1 &#61; max2;
max2 &#61; temp;
}
}
{
if (input &#61;&#61; null || input.Length < 2)
{
throw new InvalidOperationException("the input paramter is invalid, please check your input");
}
int max1 &#61; input[0], max2 &#61; input[1];
Swap(ref max1, ref max2);
for (int i &#61; 2; i < input.Length; i&#43;&#43;)
{
if (input[i] > max2)
{
max2 &#61; input[i];
Swap(ref max1, ref max2);
}
}
//if (max1 &#61;&#61; max2)
//{
// throw new InvalidOperationException("All the given values are same");
//}
return max2;
}
private static void Swap(ref int max1, ref int max2)
{
if (max1 < max2)
{
int temp &#61; max1;
max1 &#61; max2;
max2 &#61; temp;
}
}
由这里我们可以类推,如果让你实现寻找第十个大的数,你会如何做呢?