Finding an element in an array where every element is repeated odd number of times (but more than single occurrence) and only one appears once

后端 未结 5 1428
闹比i
闹比i 2020-12-12 10:25

You have an array in which every number is repeated odd number of times (but more than single occurrence). Exactly one number appears once. How do you find the number that a

5条回答
  •  感情败类
    2020-12-12 11:16

    I know that the subtext of this question is to find an efficient or performant solution, but I think that the simplest, readable code counts for a lot and in most cases it is more than sufficient.

    So how about this:

    var value = (new [] { 1, 6, 3, 1, 1, 6, 6, 9, 3, 3, 3, 3, })
        .ToLookup(x => x)
        .Where(xs => xs.Count() == 1)
        .First()
        .Key;
    

    Good old LINQ. :-)

提交回复
热议问题