c# - 在集合中找出比它们大的数

标签 c# algorithm

假设我们有一组数字,例如 { 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/

相关文章:

c# - 使用 C# 选择数组中的下一个 child

c++ - 为什么/什么时候我们应该更喜欢使用 std::swap;在 std::iter_swap(&a, &b) 上交换(a,b)?

algorithm - 如何从 b 树中删除元素?

c++ - 在大矩阵中复制图 block 的高效算法

c# - 使用继承来创建自定义的、类型安全的、空安全的集合?

c# - Browsermob 代理 - HAR 文件不如手动 HAR 完整?

algorithm - OpenCV 3.0中BackgroundSubtractorGMG算法参数含义

algorithm - 最佳多人迷宫生成算法

c# - WPF 和 Silverlight 命令实现对于 M-V-VM (M-V-P) 模式毫无用处吗?

C# resx 文件错误