c# - 如何从数组中找到第 n 个重复项

标签 c# arrays

我正在尝试解决这个问题。

基本上我需要从字符数组中选择第二个副本。

Input {'x','y','z','x','y'} output: y
Input { 'a', 'a', 'b', 'a', 'c', 'b', 'a', 'c', 'b' } Output: b
Input { 'a','a','a','b','a','c','b','a','c','b' } output: b

编辑:

Input {'a', 'b', 'c', 'b', 'a', 'c', 'b', 'a', 'c', 'b'} Output: a

我曾尝试编写这段代码,但如果第一个字符立即重复,它就会失败 :( 任何帮助纠正这个问题的方法?

 public static char returnSecondDuplicate(char[] arr)
        {
            if (arr.Length == 0)
                throw new ArgumentNullException("empty input");
            var dictionary = new Dictionary<char, int>();
            Char second = '\0';
            int duplicateCount = 0;

            for (int i = 0; i <= arr.Length - 1; i++)
            {

                if (!dictionary.ContainsKey(arr[i]))
                {
                    dictionary.Add(arr[i], 1);
                }
                else
                {
                    duplicateCount++;

                    if (duplicateCount == 2)
                    {
                        second = arr[i];
                    }
                }
            }

            return second;
        }

最佳答案

这应该很好地解决它:

var secondDuplicate = input.GroupBy( c => c)
                           .Where( g => g.Count() > 1)
                           .Skip(1)
                           .First()
                           .Key;

首先你将它们分组,然后将所有组打折为只有一个元素(因为它们不是重复的),然后取第二个(跳过第一个)

关于c# - 如何从数组中找到第 n 个重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19977848/

相关文章:

c# - 为什么我的项目连接到不同的数据源?

ios - 将两个不同类型的数组排序为一个

javascript - 如何使用 jQuery 将值插入到特定索引处的二维数组中

c# - 曼哈顿旅游问题的对角线计算

c# - 捕获从未释放的 IDisposables

c# - 映射JoinedSubclassMapping

c++ - 在本地 spoj 上的 "Edit distance"中声明二维数组会产生运行时错误?

javascript - 检查对象是否在 localStorage 中的 AngularJS 数组中

php - foreach 循环和 &$value 的引用

c# - xunit 测试不将输出保存到 xml