我会给你一个我想做的事的例子。如果我们有输入:
1 4 3 2
我要打印比其右边的所有元素大的所有数字。在这里,我们必须打印 4、3 和 2 。我已经将输入转换为数组,但是我不知道如何比较元素。
int[] numbers = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
答案 0 :(得分:1)
您可以检查当前元素是否为数组右切片的最大值:
mangesh@Mangesh:~$ pwd
/home/mangesh
mangesh@Mangesh:~$ export PATH="$PATH:/home/mangesh/Documents/flutter_data/flutter/bin/"
mangesh@Mangesh:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/mangesh/Documents/flutter_data/flutter/bin/
输出:
int[] numbers = new int[]{ 1, 4 ,3 ,2 };
var result=numbers.Where((number, i) => number == numbers.Skip(i).Max()).ToList();
答案 1 :(得分:0)
您可以使用LINQ来做到这一点,就像这样:
var numbers = new[] { 1, 4, 3, 2 };
var query =
from info in numbers.Select((n, i) => (n, i))
where numbers.Skip(info.i + 1).All(value => info.n > value)
select info.n;
工作方式是:
// Iterate over the numbers, keeping track of the index of each one
from info in numbers.Select((n, i) => (n, i))
// For each item, make sure it's greater than the ones on its right
where numbers.Skip(info.i + 1).All(value => info.n > value)
// If that's the case, select that item
select info.n;
```
答案 2 :(得分:0)
int[] numbers = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
string[] topIntegers = new string[numbers.Length];
int maximumValue = int.MinValue;
int j = 0;
for (int i = numbers.Length - 1; i >= 0; i--)
{
if (numbers[i] > maximumValue)
{
maximumValue = numbers[i];
topIntegers[j] = maximumValue.ToString();
}
j++;
}
for (int i = topIntegers.Length - 1; i >= 0; i--)
{
Console.Write($"{topIntegers[i]} ");
}
我以这种方式做到了,但是在此测试中我得到了不正确的结果:
14 24 3 19 15 17我的输出是:
24 19 17但预期是:
24 19 17
答案 3 :(得分:0)
您可以使用汇总:
int[] allNumbers = new int[] { 1, 4, 3, 2 };
int[] filteredNumbers = allNumbers.Aggregate(new List<int>(), (result, x) => {
var filteredResult = new List<int>(result.Where(y => y > x));
filteredResult.Add(x);
return filteredResult;
}).ToArray();