有人可以告诉我我的代码有什么问题吗?
基本上,在比较words1
和uniques
之后,我只需要将words1
中的唯一单词添加到words2
列表中。
在if
语句中,如果我删除了!
,它将找到匹配的词(与我需要的词相反)
List<string> Unique(string lines1 ,string lines2, char[] separators)
{
string[] words1 = lines1.Split(separators, StringSplitOptions.RemoveEmptyEntries);
string[] words2 = lines2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
List<string> uniques = new List<string>();
for (int i = 0; i < words1.Length; i++)
{
bool match;
for (int x = 0; x < words2.Length; x++)
{
if (!words1[i].Equals(words2[x]))
{
match = true;
uniques.Add(words1[i]);
break;
}
else
{
match = false;
}
}
}
return uniques;
}
答案 0 :(得分:5)
您可以对循环进行细微更改
for (int i = 0; i < words1.Length; i++)
{
bool match=false;
for (int x = 0; x < words2.Length; x++)
{
if (words1[i].Equals(words2[x]))
{
match = true;
break;
}
}
if(!match && uniques.Contains(words1[i]))
{
uniques.Add(words1[i]);
}
{
uniques.Add(words1[i]);
}
}
要使代码更短,可以使用LINQ
List<string> Unique(string lines1 ,string lines2, char[] separators)
{
string[] words1 = lines1.Split(separators, StringSplitOptions.RemoveEmptyEntries);
string[] words2 = lines2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
return words1.Except(words2).ToList();
}
答案 1 :(得分:0)
使用两个嵌套循环会导致O(n 2 )的性能下降。使用一组Union
return words1
.Union(words2)
.ToList();