假设我们有一组数字,例如 { 16,17,4,3,5,2 }。现在的目标是找到那些大于集合中其余数字的数字,同时与它们正确的元素进行比较。
表示16比17少,不能考虑。虽然 17 与 4,3 相比,5 和 2 总是更大,因此将被考虑。同样,4 虽然大于 3 但小于 5 将被丢弃。但是 5 比 2 更大。由于 2 是最右边的元素,因此将始终予以考虑。为此,我编写了以下程序并且它有效。
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var intCollection = new List<int>() { 16,17,4,3,5,2 };
var discardedElements = new List<int>();
for(int i=0;i< intCollection.Count;i++)
{
for(int j=i+1;j< intCollection.Count; j++)
{
if (intCollection[i] < intCollection[j])
{
discardedElements.Add(intCollection[i]);
}
}
}
Console.WriteLine("Successful elements are");
intCollection.Except(discardedElements).ToList().ForEach(i => Console.WriteLine("{0}", i));
Console.ReadKey();
}
}
}
结果
Successful elements are
17
5
2
但是这个程序不是一个优化的程序。对于同样的问题还有更好的算法吗?
N.B.~ 该程序虽然显然没有任何实时用途,但它有助于改进算法。
最佳答案
您可以从右到左过滤递增的数字序列
示例:
class Program
{
static void Main( String[] args )
{
var intCollection = new List<Int32>() { 16, 17, 4, 3, 5, 2 };
var intResults = new List<Int32>();
var currentMaxValue = Int32.MinValue;
for ( Int32 i = intCollection.Count - 1; i >= 0; --i )
{
if ( intCollection[ i ] > currentMaxValue )
{
currentMaxValue = intCollection[ i ];
intResults.Insert( 0, intCollection[ i ] );
}
}
Console.WriteLine( "Successful elements are" );
intResults.ForEach( i => Console.WriteLine( "{0}", i ) );
Console.ReadKey();
}
}
关于c# - 在集合中找出比它们大的数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39847600/