求三个排序数组的交集


方法1:

void GetThreeArrayComm(int A[],int lenA,intB[], 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++;

        }

        elseif(A[i] > B[j])

        {

            j++;

        }

        elseif(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;

            }

            

        }

        elseif(comm > C[k])

        {

            k++;

        }

        elseif(comm < C[k])

        {

            isFirst=false;

        }

        else

        {

            isFind= ture;

            isFirst=false;

            k++;

            cout<<comm<<"\t";

        }

    }

    cout<<endl;

    if(!isFind)

    {

        cout<<"nocomm"<<endl;

    }

}



方法2:


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;
}

你可能感兴趣的:(算法之道,笔试面试精选)