求三個排序數組的交集

方法一:

#include <iostream>
#include <stdio.h>
#include <assert.h>
using namespace std;
void GetThreeArrayComm(int A[],int lenA,int B[], int lenB, int C[],int lenC)
{
    assert(A!= NULL&&B != NULL&&C != NULL&&lenA > 0&& lenB >0&&lenC > 0);
    
    int i=0;
    int j=0;
    int k=0;
    bool isLast=false;
    bool isFirst= false;
    bool isFind=false;
    int comm=0;
    
    while(i<lenA && j <lenB && k <lenC || !isLast)
    {
        if(A[i]<B[j])
        {
            i++;
        }
        else if(A[i] > B[j])
        {
            j++;
        }
        else if(A[i] == B[j] && !isFirst)
        {
            if(isLast)
            {
                break;
            }
            isFirst=true;
            comm= A[i];
            i++;
            if(i==lenA)
            {
                i--;
                isLast=true;
            }
            
            j++;
            
            if(j==lenB)
            {
                j--;
                isLast=true;
            }
            
        }
        else if(comm > C[k])
        {
            k++;
        }
        else if(comm < C[k])
        {
            isFirst=false;
        }
        else
        {
            isFind= true;
            isFirst=false;
            k++;
            cout<<comm<<"\t";
        }
    }
    cout<<endl;
    if(!isFind)
    {
        cout<<"nocomm"<<endl;
    }
}


<span style="font-size: 24px; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">方法二:</span>
<span style="font-size:24px;">#include <iostream>
#include <stdio.h>
#include <assert.h>
using namespace std;
bool GetThreeArrayComm_update(int A[],int lenA,int B[],int lenB,int C[],int lenC)
{
	assert(A!=NULL&&B!=NULL&&C!=NULL&&lenA>0&&lenB>0&&lenC>0);
	
	int i=0;
	int j=0;
	int k=0;
	bool isLast = false;
	bool found=false;
	
	while(i<lenA && j<lenB && k<lenC )
	{
		if (A[i]<B[j])  // 使用的是小於比較,避免了邊界問題  
		{
			i++;
		}
		else           //A[i] >= B[j]
		{
			if (B[j] < C[k])
			{
				j++;
			}
			else       //B[j] >= C[k]
			{
				if (C[k] < A[i])
				{
					k++;
				}
				else //C[k]>=A[i]>=B[j]>=C[k]
				{
					 // 找到一個
					found = true;
					cout<<A[i]<<"\t";
					
					i++;
					j++;
					k++;
				}
			}
		}
	}
	
	cout<<endl;
	
	return found;
}
int main()
{
	int a[] = {1,3,5,7,9,11};
	int b[] = {1,2,3,4,5,6,7,8,9,10};
	int c[] = {1,3,5,6,9,10,12};
	
	GetThreeArrayComm_update(a,6,b,10,c,8);
	return 0;
}</span>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章