Finding common elements in two arrays of different size

后端 未结 10 896
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 18:08

I have a problem to find common elements in two arrays and that\'s of different size.

Take , Array A1 of size n and Array A2 o

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 18:53

    The Complexity of what I give is O(N*M + N).

    Also note that it is Pseudocode C And that it provides distinct values.

    eg.[1,1,1,2,2,4] and [1,1,1,2,2,2,5] Will return [1,2]

    The Complexity is N*M cause of the for loops

    + N cause of the checking if it already exists in the ArrayCommon[] (which is n size in case Array2[] contains data which duplicate Part of the Array1[] Assuming N is the size of the smaller Array (N < M).

    int Array1[m] = { Whatever };
    int Array2[n] = { Whatever };
    int ArrayCommon[n] = { };
    
    void AddToCommon(int data)
    {
        //How many commons we got so far?
        static int pos = 0; 
        bool found = false;
        for(int i = 0 ; i <= pos ; i++)
        {
            //Already found it?
            if(ArrayCommon[i] == data)
            {
                found = true;
            }
        }
        if(!found)
        {
            //Add it
            ArrayCommon[pos] = data;
            pos++;
        }
    }
    
    for(int i = 0 ; i < m ; i++)
    {
        for(int j = 0 ; j < n ; j++)
        {
            //Found a Common Element!
            if(Array1[i] == Array2[j])
                AddToCommon(Array1[i]);
        }
    }
    

提交回复
热议问题