1.4.38

上次更新:2019-04-17
发现了题解错误/代码缺陷/排版问题?请点这里:如何:提交反馈

解答

把 DoublingTest 中调用的函数稍作修改即可。

代码

ThreeSum 测试类

using System;

namespace _1._4._38
{
    /// <summary>
    /// ThreeSum 测试类。
    /// </summary>
    public static class DoubleTest
    {
        private static readonly int MAXIMUM_INTEGER = 1000000;

        /// <summary>
        /// 返回对 n 个随机整数的数组进行一次 ThreeSum 所需的时间。
        /// </summary>
        /// <param name="n">随机数组的长度。</param>
        /// <returns></returns>
        public static double TimeTrial(int n)
        {
            int[] a = new int[n];
            Random random = new Random(DateTime.Now.Millisecond);
            for (int i = 0; i < n; ++i)
            {
                a[i] = random.Next(-MAXIMUM_INTEGER, MAXIMUM_INTEGER);
            }
            Measurement.Stopwatch timer = new Measurement.Stopwatch();
            ThreeSum.Count(a);
            return timer.ElapsedTime();
        }
    }
}

ThreeSum

using System;

namespace _1._4._38
{
    /// <summary>
    /// 用暴力方法寻找数组中和为零的三元组。
    /// </summary>
    public static class ThreeSum
    {
        /// <summary>
        /// 输出所有和为零的三元组。
        /// </summary>
        /// <param name="a">输入数组。</param>
        public static void PrintAll(int[] a)
        {
            int n = a.Length;
            for (int i = 0; i < n; ++i)
            {
                for (int j = 0; j < n; ++j)
                {
                    for (int 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)
        {
            int n = a.Length;
            int count = 0;
            for (int i = 0; i < n; ++i)
            {
                for (int j = 0; j < n; ++j)
                {
                    for (int k = 0; k < n; ++k)
                    {
                        if (i < j && j < k)
                        {
                            if ((long)a[i] + a[j] + a[k] == 0)
                            {
                                count++;
                            }
                        }
                    }
                }
            }
            return count;
        }
    }
}
上一题 下一题