小欧的奇数

[题目链接](https://www.nowcoder.com/practice/aef41039765b433998812b9e9cfe02c2)

思路

本题要求从长度为 n 的数组中选出 3 个数,使它们的和为奇数。

奇偶性分析

三个数之和为奇数,只有两种情况:

  1. 1 个奇数 + 2 个偶数:奇 + 偶 + 偶 = 奇
  2. 3 个奇数:奇 + 奇 + 奇 = 奇

其他组合(2 奇 1 偶 = 偶,3 偶 = 偶)的和都是偶数。

解题条件

统计数组中奇数个数 odd 和偶数个数 even,满足以下任一条件即输出 "YES":

  • odd >= 1even >= 2
  • odd >= 3

否则输出 "NO"。

时间复杂度 O(n),空间复杂度 O(1)。

代码

C++

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n;
    scanf("%d",&n);
    int odd=0,even=0;
    for(int i=0;i<n;i++){
        int x;
        scanf("%d",&x);
        if(x%2) odd++; else even++;
    }
    if((odd>=1&&even>=2)||(odd>=3))
        puts("YES");
    else
        puts("NO");
    return 0;
}

Java

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int odd = 0, even = 0;
        for (int i = 0; i < n; i++) {
            int x = sc.nextInt();
            if (x % 2 != 0) odd++; else even++;
        }
        if ((odd >= 1 && even >= 2) || (odd >= 3))
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}

Python3

n = int(input())
a = list(map(int, input().split()))
odd = sum(1 for x in a if x % 2)
even = n - odd
if (odd >= 1 and even >= 2) or odd >= 3:
    print("YES")
else:
    print("NO")

JavaScript

const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin });
const lines = [];
rl.on('line', line => lines.push(line.trim()));
rl.on('close', () => {
    const n = parseInt(lines[0]);
    const a = lines[1].split(' ').map(Number);
    let odd = 0, even = 0;
    for (let i = 0; i < n; i++) {
        if (a[i] % 2 !== 0) odd++; else even++;
    }
    if ((odd >= 1 && even >= 2) || odd >= 3)
        console.log("YES");
    else
        console.log("NO");
});