两个数组,找到缺失的数字

two arrays, find the missing numbers

给定两个数组,第一个有 'n' 个数字,第二个有 'n-m' 个数字;第二个数组与第一个数组的顺序不同。如果有多个数字具有相同的值,则它们以原始数组中位置的顺序结束。此外,第二个数组中的所有值也可以在第一个数组中找到。我必须按照它们在第一个数组中出现的顺序找到 'm' 缺失的数字。

input:
7 3
12 34 45 29 100 87 32
100 87 12 34

output: 
45 29 32
#include <iostream>
using namespace std;

int main()
{
    int n, missing_number = 0, m, i, j, v[1201], w[1201];
    cin >> n >> m;
    for (i = 0; i < n; ++i) {
        cin >> v[i];
    }
    for (i = 0; i < n - m; ++i) {
        cin >> w[i];
    }
    for (i = 0; i < n; ++i) {
        missing_number = 1;
        for (j = 0; j < n - m; ++j) {
            if (v[i] == w[j]) {
                missing_number = -1;
            }
        }
        if (missing_number == 1) {
            cout << v[i] << " ";
        }
    }
    if (m == 0)
        cout << "there are no missing numbers";
    return 0;
}

我的代码不适用于重复数字,例如:

7 3 
2 6 1 9 3 2 4
4 1 2 3

我的输出应该在哪里:

6 9 2 

您的程序似乎输出了正确的结果。但是,我觉得我需要重构您的代码以提高其可读性并删除其中使用的不良做法。

以下与您的代码相同,但略有改进:

#include <iostream>
#include <array>
#include <limits>


int main( )
{
    std::array<int, 1201> arr1; // use std::array instead of raw arrays
    std::array<int, 1201> arr2;

    std::size_t arr1_size { }; // renamed n
    std::size_t arr2_size { }; // renamed m

    std::cin >> arr1_size >> arr2_size;

    if ( arr2_size == 0 ) // this if statement should be here to help end
    {                     // the program early on to prevent the execution
                          // of the for-loops
        std::cout << "There are no missing numbers.\n";
        return 0;
    }

    for ( std::size_t idx { }; idx < arr1_size; ++idx ) // use std::size_t
    {                                                   // for the loop counters
        std::cin >> arr1[ idx ];
    }

    for ( std::size_t idx { }; idx < arr1_size - arr2_size; ++idx )
    {
        std::cin >> arr2[ idx ];
    }

    for ( std::size_t arr1_idx { }; arr1_idx < arr1_size; ++arr1_idx )
    {
        bool isNumberMissing { true }; // this should be of type bool

        for ( std::size_t arr2_idx { }; arr2_idx < arr1_size - arr2_size; ++arr2_idx )
        {
            if ( arr1[ arr1_idx ] == arr2[ arr2_idx ] )
            {
                isNumberMissing = false;

                // this is my trick for solving your code's bug
                arr2[ arr2_idx ] = std::numeric_limits<int>::min( );

                break; // break here to improve performance
            }
        }

        if ( isNumberMissing )
        {
            std::cout << arr1[ arr1_idx ] << " ";
        }
    }

    std::cout << '\n';
}

示例 input/output #1:

7 3
12 34 45 29 100 87 32
100 87 12 34
45 29 32

示例 input/output #2:

7 3
2 6 1 9 3 2 4
4 1 2 3
6 9 2

注意:参见Why is "using namespace std;" considered bad practice?