这是我今天遇到的一道面试题:
"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();
关于c# - 返回在其他 List<string> 中仅出现一次的元素 List<string> 的微观优化和最优雅的方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34035848/