private int GetModeNum(List<int> listValue) { List<int> listName = new List<int>(); //众数 List<int> listNum = new List<int>(); //众数的数量 int index = 0; foreach (var i in listValue) { int count = 0; if (!listName.Contains(i)) { foreach (var j in listValue) { if (i == j) { count++; } } listName.Add(i); listNum.Add(count); index++; } } int max = 0, maxCount = 0, maxIndex = 0; for (int i = 0; i < index; i++) { max = max > listNum[i] ? max : listNum[i]; } for (int i = 0; i < index; i++) { if (max == listNum[i]) { maxIndex = i; maxCount++; } } if (maxCount > 0 && maxCount <= 1) { return listName[maxIndex]; } else { return -1; } }
//调用 int a = this.GetModeNum(new List<int>() { 1, 2, 28, 36, 2, 1, 5, 1, 18, 28, 6, 15, 2, 2, 5, 5, 5,5 }); if (a != -1) { Console.WriteLine("最多的数为:" + a); } else { Console.WriteLine("最多的数有重复!"); } Console.ReadLine();
世界上最可怕事情是比我们优秀的人比我们还努力