查找序列中的最小奇数和最大偶数

时间:2019-09-29 09:41:50

标签: c++

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

输入:

包含整数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?

3 个答案:

答案 0 :(得分:1)

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

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,则将为-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';

答案 1 :(得分:0)

minmax应该由不能按顺序的值初始化,否则,您将无法检测到,找到了该值,或者自初始化以来它没有发生变化

答案 2 :(得分:0)

任务说明建议使用固定大小的数组(106个元素),其中 min max 是最小奇数和最大偶数的索引,因为没有提及数字的值(它们可能全为负数,甚至为-1,因此没有安全的最小和最大初始值)。

如果不想保留所有数字的副本,则可以使用两个布尔变量作为标记来标记最小/最大值是否已初始化:

<ResourceDictionary x:Key="MaterialDesign">
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.Blue.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Indigo.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>