找到两个成对给定元素之间的最大距离

时间:2017-04-01 12:37:59

标签: c# arrays algorithm

此代码旨在找到两个元素之间的最小距离。如下例所示,3和3之间的最小距离应返回5但我需要 最远的一个不是最近的一个,我应该找到3号和3号之间的最大距离?

   internal class MinimumDistance
{
    internal virtual int minDist(int[] arr, int n, int x, int y)
    {
        int i, j;
        int min_dist = int.MaxValue;
        for (i = 0; i < n; i++)
        {
            for (j = i + 1; j < n; j++)
            {
                if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > Math.Abs(i - j))
                {
                    min_dist = Math.Abs(i - j);
                }
            }
        }
        return min_dist;
    }

    public static void Main(string[] args)
    {
        MinimumDistance min = new MinimumDistance();
        int[] arr = new int[] { 3, 2, 4, 2, 6, 5, 3, 6, 5, 4, 8, 3 };
        int n = arr.Length;
        int x = 3;
        int y = 3;

        Console.WriteLine("Minimum distance between " + x + " and " + y + " is " + min.minDist(arr, n, x, y)); //return the nearest 3 so it will be 5
    }
}

1 个答案:

答案 0 :(得分:0)

此代码应该:

internal class MaximumDistance
{
    internal virtual int maxDist(int[] arr, int n, int x, int y)
    {
        var max_dist = int.MinValue;
        for (var i = 0; i < n; i++)
            for (var j = i + 1; j < n; j++)
                if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && max_dist < Math.Abs(i - j))
                    max_dist = Math.Abs(i - j);
        return max_dist;
    }

    public static void Main(string[] args)
    {
        var max = new MaximumDistance();
        var arr = new int[] { 3, 2, 4, 2, 6, 5, 3, 6, 5, 4, 8, 3 };
        var n = arr.Length;
        var x = 3;
        var y = 3;

        Console.WriteLine("Maximum distance between " + x + " and " + y + " is " + max.maxDist(arr, n, x, y));
    }
}