有100万个数字(1到9),其中只有1个数字重复2次,如何快速找出该数字
rt, C# codes as below:
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
for (int i = 1; i < 10; i++)
{
for (int j = 0; j < i; j++)
{
list.Add(i);
}
list.Add(1);
list.Add(1);
}
Console.WriteLine(GetNum(list));
Console.ReadKey();
}
static int GetNum(List<int> listNums)
{
bool[] ifRemoved = new bool[9];
int[] counterTimes = new int[9];
int movedNum = 0;
foreach (int i in listNums)
{
if (i <= 0 || i > 9)
throw new System.FormatException(string.Format("Unexpected num value {0}!", i));
if (ifRemoved[i - 1] == false)
{
counterTimes[i - 1]++;
if (counterTimes[i - 1] > 2)
{
ifRemoved[i - 1] = true;
movedNum++;
if (movedNum == 8)
{
for (int j = 0; j < 9; j++)
{
if (ifRemoved[j] == false)
return j + 1;
}
}
}
}
}
for (int j = 0; j < 9; j++)
{
if (counterTimes[j] == 2)
return j + 1;
}
throw new System.ArgumentException("There is no suitable num in the param array!");
}
}
}