2016-11-29 78 views
-1

我在我的數組中找到次數最多的問題。事情是,它不適用於我所有的示例。 當我從鍵盤讀取數字後,我把它們放在方法test然後我對它們進行排序..例如:(用戶輸入)1,2,3,4,5,6,7,8,9,10 exit:10,9,.. 3,2,1 現在我想要顯示的第二大數與循環.. **任務是:找到第二大數字,如果可能的話,如果不是CW(「錯誤」) **在數組中找到第二個最大值

代碼評論//這裏我不知道如何扭轉正確的那部分代碼。

我希望我的問題是有道理的......

public static int test(int[] polje) 
    { 

     int temp = 0; 
     Console.WriteLine(); 
     for (int c = 0; c < polje.Length; c++) 
     { 
      for (int b = c + 1; b < polje.Length; b++) 
      { 
       if (polje[c] > polje[b]) 
       { 
        temp = polje[c]; 
        polje[c] = polje[b]; 
        polje[b] = temp; 

       } 

      } 

     } 

     int secondlargest = 0; 



     //HERE 

     for (int i = polje.Length - 1; i >= 0; i--) 
     { 
      if (polje[polje.Length - 2] == polje[polje.Length - 1] || polje[polje.Length - 2] == 0) 
      { 
       Console.WriteLine("Wrong!"); 
       break; 
      } 
      else 
      { 
       Console.WriteLine("Second largest number is :{0}", polje[polje.Length - 2]); 
       secondlargest = polje[polje.Length - 2]; 
       break; 
      } 
     } 


     return secondlargest; 

    } 
    static void Main(string[] args) 
    { 

     int[] polje = new int[10]; 
     Console.WriteLine("Enter values"); 
     for (int i = 0; i < 10; i = i + 1) 
     { 

      polje[i] = int.Parse(Console.ReadLine()); 
      if (polje[i] == 0) 
      { 
       break; 
      } 
     } 
     test(polje); 

     Console.ReadLine(); 
    } 
} 

}

+1

這功課嗎?因爲你使用List和排序,或者LINQ和OrderByDescending並且用Take(2)來獲得兩個最大的值。 –

+0

如果你已經對它們進行了排序,第二個循環的重點是什麼?根據您是按升序還是降序排序,只要您的數組有兩個以上的記錄,您可以選擇數組的第二個索引或數組的第二個索引。 – RizJa

+3

http://stackoverflow.com/questions/14810444/find-the-second-maximum-number-in-an-array-with-the-smallest-complexity – Damith

回答

3

這是非常簡單的:

var secondMaxValue = yourArray.OrderByDescending(x=> x).Skip(1).FirstOrDefault(); 
+4

爲什麼downvote?這是做這件事的好方法。 – Grax

+0

您應該提及'使用System.Linq;'是必需的 – Grax

+1

如果有兩個相同的數字,並且您不希望可以使用Distinct()。然而,在這個問題中沒有解釋這種情況究竟需要什麼。 –

0
int GetSecondLargest(int[] a){ 
    int a0,b0; 
    for(int i = 0; i <a.Length;i++){ 
      if(a[i] > a0){ 
        b0 = a0; 
        a0 = a[i]; 
      }else if(a[i] > b0) b0 = a[i]; 
    } 
    return b0; 

編輯:格式是可怕的,但這個想法是你保持最大的價值,並得到它下面的一個,而不是使用基本條件。沒有Linq需要。

+0

你錯過了一個'else if(a [i]> b0)b0 = a [i];' – juharr

+0

謝謝,格式化讓我困惑了一下 – maximdumont