List<string> list1 = new List<string>() { "0", "1" };
List<string> list2 = new List<string>() { "1", "0" };
如何比较上面两个集合list1、list2,它们是否相等
给出的条件是:只要其元素的个数、内容相等,就算相等,而不管元素的排序、索引值是否相等。
比如 { "0", "1" }与{ "1", "0" }算是相等的,{ "4", "5" }与{ "5", "4" } 也是相等的如何比较?
List<string> list2 = new List<string>() { "1", "0" };
如何比较上面两个集合list1、list2,它们是否相等
给出的条件是:只要其元素的个数、内容相等,就算相等,而不管元素的排序、索引值是否相等。
比如 { "0", "1" }与{ "1", "0" }算是相等的,{ "4", "5" }与{ "5", "4" } 也是相等的如何比较?
public static bool isEqual(List<string> list1, List<string> list2)
{
list1.Sort();
list2.Sort();
if (list1.Count == list2.Count)
{
int i = 0;
foreach (string str in list1)
{
if (str != list2[i])
{
return false;
}
i++;
}
return true;
} return false;
}
if (list1.Count == list2.Count && list1.Except(list2).Count() == 0 && list2.Except(list1).Count() == 0)
{
//集合相等
}
//或者
if (list1.Count == list2.Count && list1.All(x => list2.Contains(x)) && list2.All(x => list1.Contains(x)))
{
//集合相等
}
list1.Count == list2.Count && list1.OrderBy(x => x).Zip(list2.OrderBy(x => x), (x, y) => x == y).All(x => x == true);
protected void Page_Load(object sender, EventArgs e)
{
List<string> listA = new List<string>() { "0", "1" };
List<string> listB = new List<string>() { "1", "0" };
int count = listA.Except(listB).ToList().Count;//这一句就够了
if (count == 0)
{
Response.Write("相等"); return;
}
Response.Write("不相等");
}//如果结合的结构相同,直接去他们差集或者交集就可以很好的得到答案了
比如List<int> list1 = new List<int>() { 1, 1, 2, 3, 4 };
List<int> list2 = new List<int>() { 1, 2, 3, 4, 5 };
int count = list1.Except(list2).Count(); //count为0
谢谢。取差集确实欠考虑了。还是排序比较稳妥。
list1.Count == list2.Count && list1.OrderBy(x => x).SequenceEqual(list2.OrderBy(x => x))
复杂度明显是最好N ,最坏N^2 .
当然复杂度按最坏考虑是N^2
如果排序的话就太悲剧了没有必要排序
算法复杂度基本上就是O(M+N)
hash(set) = sum(hash(e) for e in set)