gpt4 book ai didi

c# - 最大递增序列

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:23:24 25 4
gpt4 key购买 nike

我试图编写一个程序来查找数组中相等元素的最大序列。例如:

输入:2, 1, 1, 2, 3, 3, 2, 2, 2, 1

结果:2, 2, 2

using System;
using System.Collections.Generic;

class MaximalSequence
{
static void Main()
{
string[] array = Console.ReadLine().Split(new[] { ", " }, StringSplitOptions.None);
string previous = string.Empty;
List<string> sequence = new List<string>();
List<string> tempSequence = new List<string>();
for (int i = 0; i < array.Length; i++)
{
if (array[i] != previous)
{
tempSequence.Add(previous);
if (tempSequence.Count > sequence.Count)
{
sequence = tempSequence;
}
tempSequence.Clear();
}
else
{
tempSequence.Add(previous);
}
previous = array[i];
}
Console.WriteLine(string.Join(", ", sequence));
}
}

问题是由于某些原因 tempSequence.Clear(); 两个列表都被清除了。

最佳答案

就像其他人指出的那样,List是引用类型,所以赋值是通过引用赋值的。这意味着两个变量都在更改相同的底层对象(因此 .Clear 清除了两个列表)。

解决方案是制作一个具有相同内容的单独对象(也称为深拷贝)。 List提供构造函数 public List(IEnumerable<T> collection) 从另一个集合(List)复制元素。

在您的代码中,替换 sequence = tempSequence;

sequence = new List<string>(tempSequence);

查看此 .NET Fiddle

关于c# - 最大递增序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29610597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com