什么是返回List <string>元素的微优化和最优雅方式,这些元素仅在其他List <string>中出现一次

use*_*578 4 .net c# algorithm

这是我今天面试的一个问题:

"给定一个字符串列表,返回一个只有唯一字符串的列表"

我很好奇Skeet认证的答案是什么.

我自己的答案是

public static List<string> sans_repeats ( List<string> input ) 
{
    Dictoinary<string,int> counter = new Dictionary<string,int>();
    List<string> output = new List<string>();
    foreach ( string S in input ) 
    {
       if ( counter.HasKey(S) ) counter[S] = 1;
       else ++count[S];
    }     
    foreach ( KeyValuePair<string,int> entry in counter ) 
       if ( entry.Value == 1 ) output.Add(entry.Key);
    return output;
}
Run Code Online (Sandbox Code Playgroud)

和采访说

"嗯,这是一种方法......"

在一个听起来居高临下的声音中,好像我做错了什么.

  • 它有什么逻辑错误吗?
  • 有没有办法实现更高内存和处理效率的解决方案?
  • 面试官是否可能正在寻找LINQ-esque解决方案?他为什么不喜欢我的?
  • 有没有办法让这个更紧凑?

shr*_*t18 6

基于更新的问题,这是LINQ的一种方式:

var src = new List<string>() { "dog", "cat", "elephant", "dog", "dog" } ;
src.GroupBy(x => x).Where(y => y.Count() == 1).ToList();
Run Code Online (Sandbox Code Playgroud)

演示

  • 如果底层结构不是"ICollection"(你不知道),那么调用`Count()`会非常昂贵.所以我更喜欢`!y.Skip(1).Any()`见[demo](http://rextester.com/GVLY44974). (4认同)
  • 在ToList`调用之前不应该有`.Select(g => g.Key)`. (2认同)