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?
解决方案
发布的代码,要找到最大的偶数,请按照以下步骤操作
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';
推荐阅读
- sql - 转换 UTF到 nvarchar
- gradle - Android Studio 3.1.3 gradle 问题
- javascript - 在 Express Route 中访问 promise 的值
- swift - 如何使用 Firebase 添加注释图像(mapView)?
- python - keras 训练中的 Numpy 数组错误
- html - 如何在包含图标的 div 中居中文本
- javascript - 未在导入的组件上设置 AEM 6.2 data-sly-resource resourceType
- python - 说出单词时自动语音识别
- dart - 遵循最佳实践在颤振中存储 API 密钥的正确方法
- vagrant - Vagrant up --provision 给出错误