如何返回C#中包含最大元素的数组?

时间:2012-10-28 13:48:27

标签: c# arrays algorithm linq

我有多个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。

更新

长度没有限制,但只要任何位置的某个数字更大,所以此数组是最大的。

7 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分: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)

答案 3 :(得分:0)

我会建议“二叉搜索树”。它允许快速访问最小和最大元素。

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

每个数组都需要一棵树,还有一棵树组合了数组。

如果您计划将树木做得更大,您还可以搜索“Red-Black BST”算法,以便轻松优化树木。

编辑:

正常BST本身很快,但是在添加元素时树变得非常不平衡 - 例如:如果每个新添加的变量的值平均大于前一个变量,则最大路径将获得越来越长,而通往最低限度的道路仍然很短。红黑BST是平衡的 - 通向最远元素(包括最小和最大)的路径保持相同的短路。有一种更快的BST类型,但据我所知,它们很难编码。

但如果您打算使用红黑BST,我建议您先掌握通常的BST。

答案 4 :(得分: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;
}

答案 5 :(得分: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;
    }
}

然后你可以像这样搜索max:

        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();

答案 6 :(得分: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;
}

上面的函数返回一个最高的int数组列表。例如,如果你尝试,

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);