C语言集合运算问题:交集正常但并集功能异常求助
Hey there! Let's work through why your union function is misbehaving while your intersection works just fine. From what you described, you're expecting a sorted, duplicate-free union (0 1 2 3 4 6 9) but getting unordered results with other oddities—so let's break down the fixes you need.
Common Pitfalls in Array-Based Union Implementations
Chances are your current union code is missing one or both of these critical steps:
- Deduplication: Sets can't have duplicate elements, so you need to make sure you're not adding elements that already exist in the combined collection.
- Sorting: Your expected output is ordered, so after combining and deduplicating, you need to sort the final array.
Step-by-Step Solution
Here's a straightforward approach to implement a correct union function (using C as an example, adjust to your language of choice):
Combine Both Arrays
First, merge all elements from set A and set B into a temporary array. This gives you all elements, but with possible duplicates.Remove Duplicates
Iterate through the temporary array, keeping only unique elements. For each element, check if it's already been added to your unique list—if not, keep it.Sort the Result
Finally, sort the deduplicated array to match your expected ordered output.
Example Code Implementation
#include <stdlib.h> // Returns the union of two arrays, and sets *unionSize to the size of the result int* calculateUnion(int arrA[], int sizeA, int arrB[], int sizeB, int* unionSize) { // Step 1: Merge both arrays into a temporary array int tempSize = sizeA + sizeB; int* tempArr = (int*)malloc(tempSize * sizeof(int)); for (int i = 0; i < sizeA; i++) { tempArr[i] = arrA[i]; } for (int i = 0; i < sizeB; i++) { tempArr[sizeA + i] = arrB[i]; } // Step 2: Remove duplicates int uniqueCount = 0; for (int i = 0; i < tempSize; i++) { int isDuplicate = 0; // Check if current element is already in the unique subset for (int j = 0; j < uniqueCount; j++) { if (tempArr[i] == tempArr[j]) { isDuplicate = 1; break; } } if (!isDuplicate) { tempArr[uniqueCount++] = tempArr[i]; } } // Step 3: Sort the unique array (using bubble sort for simplicity) for (int i = 0; i < uniqueCount - 1; i++) { for (int j = 0; j < uniqueCount - i - 1; j++) { if (tempArr[j] > tempArr[j + 1]) { // Swap elements int temp = tempArr[j]; tempArr[j] = tempArr[j + 1]; tempArr[j + 1] = temp; } } } *unionSize = uniqueCount; return tempArr; }
How to Verify Your Code
Compare this to your current union implementation:
- Did you skip deduplication? That would lead to duplicate elements in the result.
- Did you forget to sort? That's why your output is unordered.
- Are your loops for checking duplicates incorrect? For example, maybe you're not checking against all already-added unique elements.
Once you add these steps, your union result should match the expected sorted, duplicate-free set you're aiming for.
内容的提问来源于stack exchange,提问作者Nor Escartin

