【问题标题】:Common elements within 2 arrays2个数组中的共同元素
【发布时间】:2021-09-21 23:03:57
【问题描述】:

我正在尝试编写一个函数,将source1 中的所有值(也存在于source2 中)复制到destination 中,然后返回复制到目标中的元素数。

int common_elements(int length, int source1[length], int source2[length], int destination[length]) 
{
    int counter = 0; 
    int i = 0; 
    while (i < length) {
        int j = 0; 
        while (j < length) {
            if ( source1[i] == source2[j]) {               
                destination[counter] = source1[i];
                counter++; 
            }        
            j++; 
        }
        i++;
    }
    return counter;
}

问题是例如给定(common_elements(5, {1,2,3,4,5}, {1,2,3,2,1}, [])),正确的输入应该是

1,2,3 
return value: 3 

但是,该程序正在考虑重复并产生:

1,1,2,2,3 
return value: 5 

这是不正确的。

我该如何补救?

【问题讨论】:

  • 先对输入数组进行排序会更容易。但除此之外,只需在添加数字之前搜索输出数组即可。
  • 您在做什么来尝试并解决重复问题?

标签: arrays c loops duplicates function-definition


【解决方案1】:

在这个while循环中

    int j = 0; 
    while (j < length) {
        if ( source1[i] == source2[j]) {               
            destination[counter] = source1[i];
            counter++; 
        }        
        j++; 
    }

您正在计算数组 source2 中与元素 source1[i] 相等的所有元素。

我可以建议以下解决方案,前提是不能在函数内更改源数组。

#include <stdio.h>

size_t common_elements( int destination[], 
                        const int source1[], 
                        const int source2[],
                        size_t n ) 
{
    size_t counter = 0; 

    for ( size_t i = 0; i < n; i++ )
    {
        size_t number = 1;
        for ( size_t j = 0; j < i; j++ )
        {
            if ( source1[i] == source1[j] ) ++number;
        }
        
        for ( size_t j = 0; number && j < n; j++ )
        {
            if ( source1[i] == source2[j] ) --number;
        }
        
        if ( number == 0 ) destination[counter++] = source1[i];
    }
    
    return counter;
}

int main(void) 
{
    enum { N = 5 };
    int source1[N] = { 1, 2, 3, 4, 5 };
    int source2[N] = { 1, 2, 3, 2, 1 };
    int destination[N];
    
    size_t n = common_elements( destination, source1, source2, N );
    
    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", destination[i] );
    }
    
    putchar( '\n' );
    
    return 0;
}

程序输出是

1 2 3 

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 2022-09-24
    • 1970-01-01
    相关资源
    最近更新 更多