Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

c++ - What changes should I make to my code to handle duplicate values in the arrays while finding their union and intersection?

I am trying to figure out how to find the union and intersection of arrays when your array contains duplicate values as in the arrays initialized in the code below. It simply produces no output at all or it takes too long to produce any output. What changes should I make to the code so that it can handle duplicate values (i.e. push duplicate values only once in the vector)?

#include <iostream>
#include <vector>
using namespace std;

void ArrayUnion(int A[], int n, int B[], int m){
vector<int> joint;
int i=0,j=0;

while(i<n && j<m){
    bool found = false;

    for (int k = 0; k < joint.size(); k++){
        if (joint[k] == A[i] || joint[k] == B[j]){
            found = true;
        }
    }

    if(found == false){
        if (A[i] < B[j]){
            joint.push_back(A[i]);
            i++;
        }
        else if(B[j]<A[i]){
            joint.push_back(B[j]);
            j++;
        }
        else if(B[j]==A[i]){
            joint.push_back(A[i]);
            i++;
            j++;
        }
    }
}

while(i < n){
    bool found = false;

    for (int k = 0; k < joint.size(); k++){
        if (joint[k] == A[i]){
            found = true;
        }
    }

    if(!found){
        joint.push_back(A[i]);
        i++;
    }
}

while (j < m){
    bool found = false;

    for (int k = 0; k < joint.size(); k++){
        if (joint[k] == B[j]){
            found = true;
        }
    }

    if (!found){
        joint.push_back(B[j]);
        j++;
    }

}

cout << "Union: ";
for(int l = 0; l<joint.size(); l++){
    cout << joint[l]  << "  ";
}
cout << endl;
}

void ArrayIntersection(int A[], int n, int B[], int m){
vector<int> common;
for(int i=0; i<n; i++){
    for (int j = 0; j < m; j++)
    {
        if(A[i] == B[j]){
            bool found = false;
            for (int k = 0; i < common.size(); i++)
            {
                if (common[k] == A[i])
                {
                    found = true;
                }

            }
            if(!found){
                common.push_back(A[i]);
            }
        }
    }
}

cout << "Intersection: ";
for(int i=0; i<common.size(); i++){
    cout << common[i] << "  ";
}
cout<<endl;
}

int main()
{
int A[4]={1,2,2,3};
int B[5]={1,2,2,50,100};

ArrayUnion(A,4,B,5);
ArrayIntersection(A,4,B,5);

return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...