假设我们有一组数字,如{16,17,4,3,5,2}。现在的目标是找到那些大于集合中其余数字的数字,同时与正确的元素进行比较。
表示16与17相比较少,无法考虑。虽然17比较4,3 5和2总是更大,因此将被考虑。同样地,将丢弃小于5的大于3的邻接。但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.~该程序虽然显然没有任何实时使用,但它有助于改进算法。
答案 0 :(得分:9)
您可以从右向左过滤并过滤递增的数字序列
示例:
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();
}
}
答案 1 :(得分:2)
以下是一个示例实现:
public static IEnumerable<int> NumbersBiggerThanTheFollowingOnes(IList<int> numbers)
{
if (numbers.Count <= 0)
yield break;
int max = numbers[numbers.Count - 1];
yield return max; // Last element is considered bigger than the "following" ones.
for (int i = numbers.Count - 2; i >= 0; --i)
{
if (numbers[i] <= max)
continue;
max = numbers[i];
yield return max;
}
}
示例测试代码:
var intCollection = new List<int>() { 18, 10, 13, 16, 17, 4, 3, 5, 2 };
Console.WriteLine(string.Join(", ", NumbersBiggerThanTheFollowingOnes(intCollection).Select(x => x.ToString())));
答案 2 :(得分:1)
您可以从右向左迭代,并保持当前最大值然后进行比较。
// Check empty intCollection
result.Add(intCollection[intCollection.Count-1]);
var currentMaxValue = intCollection[intCollection.Count-1];
for(int i = intCollection.Count - 2; i >= 0; --i) {
if (intCollection[i] > currentMaxValue) {
result.Add(intCollection[i]);
currentMaxValue = intCollection[i];
}
}