What is the micro-optimal and most elegant way to return List <string> elements that occurs only once in another List <string>
That was the interview question I had today:
"Given a list of strings, return a list of only unique strings
I'm curious what answer would be certified by Skeet.
My own answer was
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;
}
and the interview said
"Well, this is one way to do this ..."
in a voice that seemed condescending, as if I were doing something wrong.
- Is there anything logically wrong with this?
- Is there a way to achieve a more efficient solution for working with memory and processing?
- Is it possible that the interviewer is looking for a LINQ-esque solution? Why didn’t I like him?
- Is there any way to make this more compact?
+4
5
:
List<string> distinctList = input.Distinct();
https://msdn.microsoft.com/library/bb920306(v=vs.90).aspx
, , :
List<string> output = new List<string>();
foreach (string S in input)
{
if (output.Contains(S)) continue;
output.Add(S);
}
Edit
, , :
Dictionary<string, int> stringCount = new Dictionary<string, int>();
foreach (string S in input)
{
if (stringCount.ContainsKey(S))
{
stringCount[S]++;
}
else
{
stringCount.Add(S, 1);
}
}
var output = stringCount.Where(x => x.Value == 1).ToList();
+3
, , HashSet.Add true, . .
var uniqueSet = new HashSet<string>();
var duplicateSet = new HashSet<string>(input.Where(item => !uniqueSet.Add(item)));
var output = input.Where(item => !duplicateSet.Contains(item)).ToList();
0