如何在C#中返回具有最大元素的数组?

5

我有多个int数组:

1) [1 , 202,4  ,55]
2) [40, 7]
3) [2 , 48 ,5]
4) [40, 8  ,90]

我需要获取所有位置上数字最大的数组,对于我的情况,这将是数组#4。解释如下:
- 数组#2和#4在第一个位置上有最大的数字,因此在第一次迭代后,这两个数组将被返回([40,7]和[40,8,90]) - 现在,在比较前一次迭代中返回的数组的第二个位置时,我们将得到数组#4,因为8> 7 - 以此类推...
你能提出一个高效的算法吗?使用Linq会更好。
更新:
长度没有限制,但只要任何位置上的某个数字更大,那么这个数组就是最大的。

这个程序非常适合使用递归。 - Patrick Oscity
1
缺少的元素怎么办?第一个数组有4个元素,但其他数组的元素较少。规则是什么? - maximpa
@MaximPaukov,长度没有限制,但只要任何位置上的数字大于其他位置,那么这个数组就是最大的。 - theateist
1
比如说,我们来比较一下 [40, 7, 90] 和 [40, 8, 50] 这两个数组。 - Adam Kostecki
7个回答

1

LINQ并不是非常高效的(例如,请参见LINQ vs FOREACH vs FOR)。然而,它提供了极佳的可读性。如果您确实需要比LINQ提供的更好的性能,则应该在没有使用LINQ的情况下编写代码。但是,在您确定需要优化之前,不应该进行优化。

这并不是专门针对性能进行调整的,但它是一个清晰、易读的解决方案:

static int[] FindLargestArray(int[][] arrays)
{
    for (int i = 0; arrays.Length > 1 && i < arrays.Max(x => x.Length); i++)
    {
        var maxVal = arrays.Where(x => i < x.Length).Max(x => x[i]);
        arrays = arrays.Where(x => i < x.Length && x[i] == maxVal).ToArray();
    }
    return arrays[0]; //if more than one array, they're the same, so just return the first one regardless
}

根据情况,这个的表现可能已经足够好了。


1
var allArrays = new[]
{
    new[] { 1, 202, 4, 55 },
    new[] { 40, 7 },
    new[] { 2, 48, 5 },
    new[] { 40, 8, 90 }
};

查找要比较的索引。

排除第三个索引,因为没有可比较的内容, 即第一个数组中只有55:

Data

var maxElementsCount = allArrays.GroupBy(p => p.Length)
    // Find 2 at least
    .Where(p => p.Count() > 1)
    // Get the maximum
    .OrderByDescending(p => p.Count())
    .First().Key;

// 0, 1, 2
var indexes = Enumerable.Range(0, maxElementsCount);

获取切片:

Slices table

var slices = indexes.Select(i =>
    allArrays.Select((array, arrayNo) => new
    {
        ArrayNo = arrayNo,
        // null if the element doesn't exist
        Value = i < array.Length ? array[i] : (int?)null
    }))
    .ToArray();

Slices

// Get the max values in each slice
var maxValues = slices.SelectMany(slice =>
    {
        var max = slice.Max(i => i.Value);
        return slice.Where(i => i.Value == max);
    })
    .ToArray();

Max values

// Get the result array no
var arrayNumber = maxValues.GroupBy(p => p.ArrayNo)
    .OrderByDescending(p => p.Count())
    .First().Key;

var res = allArrays[arrayNumber];

Result


1

a) 不是最高效的方法,但很容易写成一行代码。

var arr1 = new int[] { 1, 202, 4, 55 };
var arr2 = new int[] { 40, 7 };
var arr3 = new int[] { 2, 48, 5 };
var arr4 = new int[] { 40, 8, 90 };

var max = new int[][] { arr1, arr2, arr3, arr4 }
           .Select(arr => new { 
                   IArray = arr, 
                   SArray = String.Join("",arr.Select(i => i.ToString("X8"))) 
           })
           .OrderByDescending(x => x.SArray)
           .First()
           .IArray;

b) 通过实现`IComparer`实现更好的效果
public class ArrayComparer : IComparer<int[]>
{
    public int Compare(int[] x, int[] y)
    {
        for(int i=0;i < Math.Min(x.Length,y.Length);i++)
        {
            if (x[i] > y[i]) return 1;
            if (x[i] < y[i]) return -1;
        }
        return x.Length - y.Length;
    }
}

var max2 = new int[][] { arr1, arr2, arr3, arr4 }
           .OrderByDescending(x => x, new ArrayComparer())
           .First();

c) 最好的选择

var arrays = new int[][] { arr1, arr2, arr3, arr4 };
var max3 = arrays[0];
ArrayComparer comparer = new ArrayComparer();
for (int i = 1; i < arrays.Length; i++)
{
    if(comparer.Compare(arrays[i],max3)>0) max3 = arrays[i];
}

d) 通过扩展“Max”来创建通用版本

var max4 = new int[][] { arr1, arr2, arr3, arr4 }
            .Max(new SOExtensions.Comparer<int>())
            .ToArray();

public static class SOExtensions
{
    public static IEnumerable<T> Max<T>(this IEnumerable<IEnumerable<T>> lists, IComparer<IEnumerable<T>> comparer)
    {
        var max = lists.First();
        foreach (var list in lists.Skip(1))
        {
            if (comparer.Compare(list, max) > 0) max = list;
        }
        return max;
    }

    public class Comparer<T> : IComparer<IEnumerable<T>> where T: IComparable<T>
    {
        public int Compare(IEnumerable<T> x, IEnumerable<T> y)
        {
            foreach(var ab in  x.Zip(y,(a,b)=>new{a,b}))
            {
                var res=ab.a.CompareTo(ab.b);
                if (res != 0) return res;
            }
            return x.Count() - y.Count();
        }
    }
}

结论

在我的测试案例中,它们的相对表现为:4000T、270T、T、6T

因此,如果您想要速度,请不要使用利用Sort/OrderBy的算法,因为其成本为O(N*Log(N))(而Max为O(N))。


0

看起来这是一个可以用递归解决的问题。

public void GetMax()
{
    var matrix = new[]
                {
                    new[] {1, 202, 4, 55},
                    new[] {40, 7},
                    new[] {2, 48, 5},
                    new[] {40, 8, 90}
                };
    var result = GetMaxRecursive(matrix).FirstOrDefault();
}

private static int[][] GetMaxRecursive(int[][] matrix, int level = 0)
{
    // get max value at this level
    var maxValue = matrix.Max(array => array.Length > level ? int.MinValue : array[level]);

    // get all int array having max value at this level
    int[][] arraysWithMaxValue = matrix
        .Where(array => array.Length > level && array[level] == maxValue)
        .ToArray();

    return arraysWithMaxValue.Length > 1
                ? GetMaxRecursive(arraysWithMaxValue, ++level)
                : arraysWithMaxValue;
}

0
我会选择传统的面向对象方法并创建一个包装器:
public class SpecialArray<T> : IComparable<SpecialArray<T>>
    where T : IComparable
{
    public T[] InternalArray { get; private set; }

    public SpecialArray(T[] array)
    {
        InternalArray = array;
    }

    public int CompareTo(SpecialArray<T> other)
    {
        int minLength = Math.Min(InternalArray.Length, other.InternalArray.Length);

        for ( int i = 0; i < minLength; i++ )
        {
            int result = InternalArray[i].CompareTo(other.InternalArray[i]);

            if ( result != 0 )
                return result;
        }

        return 0;
    }
}

然后你可以这样搜索最大值:

        var list = new[]
            {
                new SpecialArray<int>(new[] {1, 202, 4, 55}),
                new SpecialArray<int>(new[] {40, 7}),
                new SpecialArray<int>(new[] {2, 48, 5}),
                new SpecialArray<int>(new[] {40, 8, 90})
            };

        var max = list.Max();

0

完全没有 Linq 的东西:

public static List<int[]> FindTheHighestArrays(List<int[]> lst)
{
    List<KeyValuePair<int[], int>> temp = new List<KeyValuePair<int[], int>>();
    List<int[]> retList = lst;
    lst.Sort((x, y) => x.Length.CompareTo(y.Length));
    int highestLenght = lst[lst.Count - 1].Length;
    for (int i = 0; i < highestLenght; i++)
    {
        temp.Clear();

        foreach (var item in retList)
        {
            if (item.Length <= i)
                continue;

            temp.Add(new KeyValuePair<int[], int>(item, item[i]));
        }

        temp.Sort((x, y) => x.Value.CompareTo(y.Value));
        retList.Clear();
        retList.AddRange(temp.FindAll(kvp => kvp.Value == temp[temp.Count - 1].Value).ConvertAll(f => f.Key));

        if (retList.Count == 1)
            return retList;
    }

    return retList;
}

上述函数返回一个整数数组列表,这些数组是最高的。例如,如果您尝试:

1)[1, 202, 4, 55]

2)[1, 202, 4, 55]

该函数将返回两个数组,因为它们都是同样高的。如果在这种情况下只想要一个数组,那么只需要改变返回类型并返回列表的第一个元素即可。

您可以像这样调用它:

int[] a = new int[] { -1, 31, 90 };
int[] b = new int[] { -1, 31, 89 };
int[] c = new int[] { 0, 0, 90 };
List<int[]> lst = new List<int[]>() { a, b, c };

var highestArrays = FindTheHighestArrays(lst);

0
我建议使用“二叉搜索树”。它可以快速访问最小和最大元素。

http://en.wikipedia.org/wiki/Binary_search_tree

你需要为每个数组都创建一棵树,以及一棵合并这些数组的树。

如果你计划让这些树变得更大,你也可以搜索“红黑树BST”算法以进行简单的优化。

编辑:

普通的BST本身很快,但是当添加元素时,树会变得相当不平衡-例如:如果每个新添加的变量的值平均比上一个变量的值大,那么到最大值的路径会变得越来越长,而到最小值的路径仍然非常短。红黑树BST是平衡的-到最远元素(包括最小值和最大值)的路径保持同样短。还有一种更快的BST类型,但据我所知,它们很难编码。

但是,如果你要使用红黑树BST,我建议你先掌握常规BST。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接