【问题标题】:C# Length of the longest non-decreasing sequence unsortedC# 最长非递减序列的长度未排序
【发布时间】:2015-12-25 09:57:03
【问题描述】:

我有一个列表,里面有一些值

for (int i = 0; i < InputNumbers.Length; i++)
        {
            InputNumbers[i] = Convert.ToInt32(Console.ReadLine());
            LongestSequence.Add(InputNumbers[i]);
        }
        for (int i = 0; i < InputNumbers.Length; i++)
        {
            if (i > 0)
            {
                if (LongestSequence[i] < LongestSequence[i - 1])
                {
                    LongestSequence.Remove(LongestSequence[i]);
                    LongestSequence.Insert(i, null);
                }
            }
        }

如您所见,我将我的数组 InputNumbers 中的所有值添加到列表 LongestSequence 中,完成后我删除其中一些值并在替换值索引处插入“null”。所以这会创建类似边框的东西:

null
1  
2
null

我想知道这 2 个空值之间的值的长度。在这种情况下,它是 2

  • 如果输入为 1 2 3 0,则 null 将位于开头并替换零,因为 0 小于 3,并且我正在寻找最长的非递减序列

【问题讨论】:

  • 列表中是否只有两个空值?
  • 请解释这段代码的目的是什么,因为它似乎很难理解
  • 不,可能有数百个空值
  • 那么当列表中有数百个空值时应该输出什么?
  • 如果输入为 1 2 3 0,则 null 将位于开头并将替换零,因为 0 小于 3,并且我正在寻找最长的非递减序列

标签: c# arrays list indexing


【解决方案1】:

看起来像 XY 问题。您需要找到最长的非递减序列,而您已经找到了一种糟糕的方法,现在您希望我们帮助您。最好直接请求帮助最长的非递减序列。无需在设置nulls 中然后尝试在它们之间查找值。

您可以简单地执行以下操作:

List<int> current = new List<int> { Int32.MaxValue };
int[] best = new int[0];

int n = int.Parse(Console.ReadLine());   

for (int i = 0; i < n; i++)
{
    var read = int.Parse(Console.ReadLine());

    if (read < current[current.Count - 1])
    {
        if (current.Count > best.Length) best = current.ToArray();
        current.Clear();
    }

    current.Add(read);
}

if (current.Count > best.Length) best = current.ToArray();

// Here, "best" stores the best result

它看起来更清晰、透明和可读。
但是,我坚信还有许多更短、更优雅的解决方案。

【讨论】:

  • @kopelence 如果对我有用。尝试更新的代码。请注意,n 首先被读取。
猜你喜欢
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-11
  • 2018-02-19
  • 1970-01-01
相关资源
最近更新 更多