我正在尝试解决这个问题。
基本上我需要从字符数组中选择第二个副本。
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/