C#實現如何判斷一個數組中是否有重復的元素


 如何判斷一個數組中是否有重復的元素 

實現判斷數組中是否包含有重復的元素方法 這里用C#代碼給出實例

方法一:可以新建一個hashtable利用hashtable的Contains方法進行查找

 1         /// <summary>
 2         /// Hashtable 方法
 3         /// </summary>
 4         /// <param name="array"></param>
 5         /// <returns></returns>
 6         public static bool IsRepeat(int[] array)
 7         {
 8             Hashtable ht = new Hashtable();
 9             for (int i = 0; i < array.Length; i++)
10             {
11                 if (ht.Contains(array[i]))
12                 {
13                     return true;
14                 }
15                 else
16                 {
17                     ht.Add(array[i], array[i]);
18                 }
19             }
20             return false;
21         }

方法二:使用for循環進行比較  需要注意的是j<=i    如果只是等於,實際上效率偏低,有重復計算可以自己摸索,有時間我畫個圖出來,^_^(這里感謝面試官的提醒)

 1         /// <summary>
 2         /// for循環
 3         /// </summary>
 4         /// <param name="yourValue"></param>
 5         /// <returns></returns>
 6         public static bool IsRepeat2(int[] array)
 7         {
 8             for (int i = 0; i < array.Length; i++)
 9             {
10                 for (int j = 0; j < array.Length; j++)
11                 {
12                     if (j <= i)
13                     {
14                         continue;
15                     } 
16                     if (array[i] == array[j])
17                     {
18                         return true;
19                     }
20                 }
21             }
22             return false;
23         }

測試代碼:

 1         static void Main(string[] args)
 2         {
 3             int[] array = new int[] { 1,2,3,4,3,6,7,8};
 4             int[] array2 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
 5             Console.WriteLine("---------------包含重復元素----------------");
 6             bool isrepeat = IsRepeat(array);
 7             bool isrepeat2 = IsRepeat2(array);
 8             Console.WriteLine(isrepeat);
 9             Console.WriteLine(isrepeat2);
10 
11             Console.WriteLine("---------------不包含重復元素----------------");
12             bool isrepeat3 = IsRepeat(array2);
13             bool isrepeat4 = IsRepeat2(array2);
14             Console.WriteLine(isrepeat3);
15             Console.WriteLine(isrepeat4);
16             Console.Read();
17         }

運行結果:

程序源代碼工程下載

各位好漢如果有更好的方法能夠優化程序,減少計算的次數,麻煩給出,感激!


免責聲明!

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



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