You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中出现Time Limit Exceeded错误,求优化数组奇偶计数代码

Fixing Time Limit Exceeded for Odd/Even Count in Java

Hey there! Let's dig into why your code might be hitting that Time Limit Exceeded error and how to speed it up.

First, let's identify the bottleneck in your original code: the item % 2 == 0 check. While this works correctly, the modulo operation (%) is relatively slow for computers because it relies on division logic under the hood. For large arrays, this small overhead adds up quickly and can push your runtime over the time limit.

Key Optimizations to Fix Timeouts

  • Replace modulo with bitwise check: Even numbers have a 0 in their least significant binary bit, so using a bitwise AND (&) with 1 is a direct, low-level operation that's way faster than modulo.
  • Parallelize for huge arrays: For extremely large datasets (millions of elements), split the counting work across multiple threads using Java's parallel streams.
  • Optimize input reading: Slow input parsing (like using Scanner for large data) is a common hidden bottleneck—switch to BufferedReader for faster input handling.

Optimized Code (Bitwise Check)

This is the simplest and most impactful fix for most cases:

class Check {
    static void countOddEven(int a[], int n) {
        int countEven = 0;
        for (int item : a) {
            // Check if the last binary bit is 0 (even number)
            if ((item & 1) == 0) {
                countEven++;
            }
        }
        int countOdd = n - countEven;
        System.out.println(countOdd + " " + countEven);
    }
}

Parallel Stream Version (For Massive Arrays)

Use this only if your array is truly huge—parallelism has small overhead that isn't worth it for small datasets:

import java.util.Arrays;

class Check {
    static void countOddEven(int a[], int n) {
        // Split counting across multiple threads
        long countEven = Arrays.stream(a)
                               .parallel()
                               .filter(item -> (item & 1) == 0)
                               .count();
        long countOdd = n - countEven;
        System.out.println(countOdd + " " + countEven);
    }
}

Fast Input Reading Example

If you're reading large input data, replace Scanner with BufferedReader to avoid input-related delays:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int[] a = new int[n];
        String[] inputParts = br.readLine().split(" ");
        
        for (int i = 0; i < n; i++) {
            a[i] = Integer.parseInt(inputParts[i]);
        }
        
        Check.countOddEven(a, n);
    }
}

Final Tips

  • Start with the bitwise operation fix first—it's the easiest win for most scenarios.
  • Test parallel streams only if your array size is in the millions (otherwise, stick to the sequential loop).
  • Always verify your input handling if you're still hitting timeouts—slow input is often the root cause.

内容的提问来源于stack exchange,提问作者Prerna Bhadoria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:34:51