热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

给定一个数组,寻找次大的数(1)

给定一个数组,寻找次大的数,你会如何实现?代码internalstaticintFindSecondMaximum(int[]input){if(inputnull||input.

给定一个数组,寻找次大的数,你会如何实现?

ExpandedBlockStart.gif代码
 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;
            }
        }

 

由这里我们可以类推,如果让你实现寻找第十个大的数,你会如何做呢?

 


转载于:https://www.cnblogs.com/DivineEagle/archive/2011/01/27/Nisten.html


推荐阅读
author-avatar
寻找4s_666
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有