如何判断一个数组中是否有重复的元素
实现判断数组中是否包含有重复的元素方法 这里用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 }
运行结果:
程序源代码工程下载
各位好汉如果有更好的方法能够优化程序,减少计算的次数,麻烦给出,感激!