1.4.38 #
解答 #
把 DoublingTest 中调用的函数稍作修改即可。
代码 #
ThreeSum 测试类
public static class DoubleTest
{
private static readonly int MaximumInteger = 1000000;
/// <summary>
/// 返回对 n 个随机整数的数组进行一次 ThreeSum 所需的时间。
/// </summary>
/// <param name="n">随机数组的长度。</param>
/// <returns></returns>
public static double TimeTrial(int n)
{
var a = new int[n];
var random = new Random(DateTime.Now.Millisecond);
for (var i = 0; i < n; i++)
{
a[i] = random.Next(-MaximumInteger, MaximumInteger);
}
var timer = new Measurement.Stopwatch();
ThreeSum.Count(a);
return timer.ElapsedTime();
}
}
ThreeSum
public static class ThreeSum
{
/// <summary>
/// 输出所有和为零的三元组。
/// </summary>
/// <param name="a">输入数组。</param>
public static void PrintAll(int[] a)
{
var n = a.Length;
for (var i = 0; i < n; i++)
{
for (var j = 0; j < n; j++)
{
for (var k = 0; k < n; k++)
{
if (i < j && j < k)
{
if ((long)a[i] + a[j] + a[k] == 0)
{
Console.WriteLine($"{a[i]} + {a[j]} + {a[k]}");
}
}
}
}
}
}
/// <summary>
/// 计算和为零的三元组的数量。
/// </summary>
/// <param name="a">输入数组。</param>
/// <returns></returns>
public static int Count(int[] a)
{
var n = a.Length;
var count = 0;
for (var i = 0; i < n; i++)
{
for (var j = 0; j < n; j++)
{
for (var k = 0; k < n; k++)
{
if (i < j && j < k)
{
if ((long)a[i] + a[j] + a[k] == 0)
{
count++;
}
}
}
}
}
return count;
}
}