4

私は問題を解決しようとしていました。

基本的に、文字配列から 2 番目の複製を選択する必要があります。

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;
        }
4

4 に答える 4

2

特定のケースで機能する一般的な拡張メソッドを次に示します。

public static T GetNthDuplicate<T>(this IEnumerable<T> source, int n)
{
    HashSet<T> hashSet = new HashSet<T>();
    return source.Where(item => !hashSet.Add(item))
                 .Distinct().Skip(n - 1) //one based index
                 .FirstOrDefault();
}
于 2013-11-14T12:59:58.757 に答える
2

これでうまく解決するはずです:

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

最初にそれらをグループ化し、次にすべてのグループを 1 つの要素のみで割り引き (それらは重複していないため)、次に 2 つ目の要素を取得します (最初の要素をスキップして)。

于 2013-11-14T12:43:17.953 に答える