如何在C#中不使用任何集合和LINQ就可以使集补和集差呢?我们有两个数组int[]arr1=new int{1,2,3,4};int[]arr2=新int{3,4,5,6,7,8};补码必须为arr3{5,6,7,8},差分必须为arr4{1,2}。我试过把一套加到另一套,然后找到都柏林,但没能成功。
int numDups = 0, prevIndex = 0;
for (int i = 0; i < array.Length; i++)
{
bool foundDup = false;
for (int j = 0; j < i; j++)
{
if (array[i] == array[j])
{
foundDup = true;
numDups++; // Increment means Count for Duplicate found in array.
break;
}
}
if (foundDup == false)
{
array[prevIndex] = array[i];
prevIndex++;
}
}
// Just Duplicate records replce by zero.
for (int k = 1; k <= numDups; k++)
{
array[array.Length - k] = '\0';
}
您可以创建两个列表,一个用于补数,另一个用于差数,迭代数组A并检查哪些包含在B中,哪些不包含在B中,反之亦然,迭代B并检查哪些存在于A中。
int[] arr1 = new int[]{ 1,2,3,4 };
int[] arr2 = new int[]{ 3,4,5,6,7,8 };
List<int> diff = new List<int>();
List<int> comp = new List<int>();
//Compute difference
foreach(int i in arr1)
{
bool found = false;
foreach(int i2 in arr2)
{
if(i == i2)
{
found = true;
break;
}
}
if(!found)
diff.Add(i);
}
//Compute complement
foreach(int i in arr2)
{
bool found = false;
foreach(int i2 in arr1)
{
if(i == i2)
{
found = true;
break;
}
}
if(!found)
comp.Add(i);
}
//This uses Linq to transform lists into arrays, if you can't use you can create
//these manually.
int[] arr3 = comp.ToArray();
int[] arr4 = diff.ToArray();