Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - 在两个数组中查找共同的元素(Find common elements in two arrays)

This algorithms here is to find the common elements in two arrays.

(这里的算法是找到两个数组中的公共元素。)

Everything seems okay until I enter

(一切顺利,直到我进入)

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

The output should be

(输出应为)

key[]={4}

Instead, it gives:

(相反,它给出:)

key[]={4,4}

How can I fix it?

(我该如何解决?)

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);
}
  ask by Phineas translate from so

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

1 Reply

0 votes
by (71.8m points)

Index 0 is a valid index which function seqSearch may return.

(索引0seqSearch函数可能返回的有效索引。)

Use -1 instead (also in if (seqSearch(key, sizekey, a[i]) == 0) ).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...