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

标签 c# .net algorithm

这是我今天遇到的一道面试题:

"Given a list of strings, return a list of only the unique strings"

我很好奇经双向飞碟认证的答案是什么。

我自己的回答是

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

和采访说

"Well, that's one way to do it ..."

用一种居高临下的声音,好像我做错了什么一样。

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

最佳答案

根据更新的问题,这里有一种使用 LINQ 的方法:

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

Demo

关于c# - 返回在其他 List<string> 中仅出现一次的元素 List<string> 的微观优化和最优雅的方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34035848/

相关文章:

c# - 使用最小起订量 : Mock object update automatically?

c# - 如何在 C# 中指定 RGB 值的范围

.net - 更新数据而不检索

algorithm - 连通分量计数算法的运行时间

algorithm - 动态规划和贪心法有什么区别?

c# - 如何在C#Xamarin中获取单元格

c# - 如何正确捕获调用存储过程的返回值

c# - 如何从其 valueMember 设置组合框基的选定索引? (C# 窗口窗体)

c# - 声明一个 var 而不初始化它......只是还没有

c - 这是什么排序算法?