簡體   English   中英

查找兩個數組中的公共元素

[英]Find common elements in two arrays

這里的算法是找到兩個數組中的公共元素。 在我進入之前一切似乎都很好

a[]={4,3,4,2}
b[]={4,1}

輸出應該是

key[]={4}

相反,它給出:

key[]={4,4}

我該如何解決?

int seqSearch(int arr[], int size, int key) {
    for (int i = 0; i < size; i++)
        if (arr[i] == key)
            return i;
    return 0;
}
void findDup(int a[], int b[], int& size1, int& size2, int key[], int& sizekey)
{
    for (int i = 0; i < size1; i++)
        for (int j = 0; j < size2; j++)
            if (a[i] == b[j])
                if (seqSearch(key, sizekey, a[i]) == 0)
                {
                    key[sizekey] = a[i];
                    sizekey++;
                }   
}
int main() {
    int a[max], b[max], key[100], size1, size2, sizekey=0;
    findDup(a, b, size1, size2, key, sizekey);
}

索引0是函數seqSearch可能返回的有效索引。

使用-1代替(也在if (seqSearch(key, sizekey, a[i]) == 0) )。

使用 std::unordered_set 代替鍵作為“int 數組”。 因此,您也不需要單獨的計數變量,它也不會接受那里的重復項。

在 seqSerach 中以 bool 形式返回值,這意味着該值是否已存在於數組中。 相應地在你的第二個函數中使用它。 問題是 0 是您要返回的有效整數。

從輸出數組中刪除重復的元素

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM