我本来希望这段代码能够快速执行,但是对于 5000 个元素的列表,它在我杀死它之前运行了超过 20 分钟。
是因为 list.contains() 吗?
有任何想法吗?
public static int PNum(int N)
{
List<int> result = new List<int>();
for (int i = 1; i <= N; i++)
result.Add(i * (3 * i - 1) / 2);
int len = result.Count;
int minDiff = 10000;
int sum = 0, diff = 0;
for (int i = 0; i <= len - 1; i++)
{
for (int j = i + 1; j <= len - 1; j++)
{
diff = result[j] - result[i];
if (result.Contains(diff))
{
sum = result[i] + result[j];
if (result.Contains(sum))
{
if (diff < minDiff)
diff = minDiff;
}
}
}
}
return minDiff;
}