首页 > 解决方案 > 在序列中找到最小奇数和最大偶数

问题描述

我正在尝试这个非常简单的问题:

输入:

包含一个整数 n (n ≤ 10^6) - 序列中元素的数量,在它之后 ai (1<=i<=n) - 序列中的元素

输出:

写出序列的最小奇数和最大偶数。如果没有这样的数字,那么写“-1”而不是这个数字。

输入格式:

5

1 2 3 4 5

输出:1 4

我试过的是这个,但还是过不了网上的评委。

#include <iostream>
//#include <cmath>

using namespace std;
int main()
{
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    int n, a, min, max;
    cin >> n;
    min = INT16_MAX; max = 0;
    for (int i = 0; i < n; i++)
    {
        cin >> a;
        if (a >= max && a % 2 == 0) { max = a; }
        if (a <= min && a % 2 != 0) { min = a; }
    }

    if (min == INT16_MAX && min != 1) { min = -1; }
    if (max == 0) { max = -1; }
    cout << min << " " << max;
    return 0;
}

为了更好地理解需要什么,如果输入:

5

2 4 2 5 4

输出应该是:-1 4 还是 5 4?

标签: c++

解决方案


发布的代码,要找到最大的偶数,请按照以下步骤操作

int max = 0;
// ...
{
    // ...
    if (a >= max && a % 2 == 0) { max = a; }
}

if (max == 0) { max = -1; }

但是,引用的问题似乎没有指定输入值的范围。因此,对于每个小于零的偶数,这都会给出错误的结果。

用于查找最小值的逻辑中存在类似的问题,该逻辑假定所有奇数值都小于或等于INT16_MIN


如果输入 (...) 2 4 2 5 4 输出应该是:-1 4 还是 5 4?

根据我对引用问题的理解,输出应该是 5 4。如果数字是,那么输出应该是 -1 4,例如 2 4 2 6 4(没有奇数)。


为确保找到的极值有效,您可以使用几个标记值,即不可能是(最小)奇数和不可能是(最大)偶数的值:

const int odd_sentinel = 0;     // It isn't odd...
const int even_sentinel = -1;   // It's not even
int min_odd = odd_sentinel;
int max_even = even_sentinel;

int x;
while ( std::cin >> x )
{
    if ( x % 2 )
    {
        if ( min_odd == odd_sentinel  ||  x < min_odd )
            min_odd = x;
    }
    else
    {
        if ( max_even == even_sentinel  ||  x > max_even )
            max_even = x;
    }
}

std::cout << (min_odd == odd_sentinel ? -1 : min_odd) << ' '
          << (max_even == even_sentinel ? -1 : max_even) << '\n';

推荐阅读