我有一个List<int[]>
,我是通过将整数数组分成4组来填充的。现在,我需要获取数组中两个最高数字的差。我尝试了Array.Sort,但是在继续操作方面却遇到了麻烦。
到目前为止我做了什么?
public static void solution(int[] T)
{
List<int[]> splitted = new List<int[]>();//This list will contain all the splitted arrays.
int lengthToSplit = T.Length / 4;
int arrayLength = T.Length;
for (int i = 0; i < arrayLength; i = i + lengthToSplit)
{
int[] val = new int[lengthToSplit];
if (arrayLength < i + lengthToSplit)
{
lengthToSplit = arrayLength - i;
}
Array.Copy(T, i, val, 0, lengthToSplit);
splitted.Add(val);
}
//this is the part where I must get the difference between the two highest numbers in an integer array and put into another list.
foreach (int[] integerarray in splitted)
{
//get the difference of the two highest numbers per integer array and place it on another List<int>
}
}
答案 0 :(得分:2)
获取整数数组中两个最高数字之间的差 并放入另一个列表
您可以使用LINQ和Math.Abs
:
List<int> differenceList = splitted
.Select(list => list.OrderByDescending(i => i).Take(2).ToArray())
.Select(highestTwo => Math.Abs(highestTwo[0] - highestTwo[1]))
.ToList();