计算列表中的重复数字

Rik*_*Rik 8 c# list

我有一个清单:

int list = { 1,1,2,3,4,4,5,7,7,7,10};
Run Code Online (Sandbox Code Playgroud)

现在我需要制作一个计算双数的程序.当前面的数字相同时,数字是两倍.我希望你明白.因此1是双倍,4是双打,我们在7,7,7中得到2双.

Ani*_*Ani 26

这是LINQ的解决方案:

var doubles = list.Skip(1)
                  .Where((number, index) => list[index] == number);
Run Code Online (Sandbox Code Playgroud)

这将通过跳过列表的第一个成员创建另一个序列,然后查找具有相同索引和相同值的两个序列中的元素.它将以线性时间运行,但仅限于列表提供O(1)索引访问.

  • 想象一下,将其作为作业回答,然后向班级(和老师)解释... mwahahaha (9认同)
  • 肯定是+1.答案是简洁,正确(没有经过测试,但我冒了风险),非常聪明,并正确地论证了为什么它在线性时间运行. (2认同)

Jon*_*eet 7

这是一种相对简单的方法,只在序列上迭代一次,并且适用于任何序列(不仅仅是列表):

public IEnumerable<T> FindConsecutiveDuplicates<T>(this IEnumerable<T> source)
{
    using (var iterator = source.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            yield break;
        }
        T current = iterator.Current;
        while (iterator.MoveNext())
        {
            if (EqualityComparer<T>.Default.Equals(current, iterator.Current))
            {
                yield return current;
            }
            current = iterator.Current;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是另一个更简单的一点,因为它只是一个LINQ查询,但它在Where子句中使用了副作用,这是令人讨厌的:

IEnumerable<int> sequence = ...;

bool first = true;
int current = 0;
var result = sequence.Where(x => {
   bool result = !first && x == current;
   current = x;
   first = false;
   return result;
});
Run Code Online (Sandbox Code Playgroud)

第三种选择,有点干净,但使用的SelectConsecutive方法基本上SelectPairs来自这个答案,但重命名为稍微清晰:)

IEnumerable<int> sequence = ...;
IEnumerable<int> result = sequence.SelectConsecutive((x, y) => new { x, y })
                                  .Where(z => z.x == z.y);
Run Code Online (Sandbox Code Playgroud)

  • 你是什​​么意思"使用副作用"? (2认同)
  • 我的眼睛在流血. (2认同)

tee*_*yay 6

每个人似乎都试图找到好的方法,所以这是一个非常糟糕的方式:

List<int> doubles = new List<int>();
Dictionary<int, bool> seenBefore = new Dictionary<int, bool>();

foreach(int i in list)
{
    try
    {
        seenBefore.Add(i, true);
    }
    catch (ArgumentException)
    {
        doubles.Add(i);
    }
}

return doubles;
Run Code Online (Sandbox Code Playgroud)

请不要那样做.