獲取數組中的第二大的數字


當年面試一家公司,面試官問我:一個int類型的數組怎么獲取里面第二大的數字?

給了我一張紙和一支筆讓我寫一個方法,我想了想便寫了一個方法:

  int[] arr = new int[] {8,10,10,8,9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

 public int GetSecondNum(int[] arr)
        {
            int max = 0;
            int second = 0;
            foreach (var item in arr)
            {
                if(item>max)
                {
                    max = item;
                }
            }
            foreach (var item in arr)
            {
                if (item > second && item <max)
                {
                    second = item;
                }
            }
            return second;
        }

然后問我能不能優化一下你的代碼,我當然回答可以了,尷尬的就是我想了半天也想不出來,當時腦子一片空白........;

最后無奈的說:可以優化,但是我現在想不到!

現在回頭再看,這不是可以這樣優化嘛:

 int[] arr = new int[] {8,10,10,8,9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

 public int GetSecondNum(int[] arr)
        {
            int max = 0;
            int second = 0;
            foreach (var item in arr)
            {
                max = max > item ? max : item;
                second = (item > second && item < max) ? item : second;
            }
            return second;
        }

一個半路出家的小菜鳥,一路磕磕絆絆,慢慢的在成長,每天學習一點,每天充實一點!

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM