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

CodingBat zeroMax挑战的Java Stream API实现方法咨询

zeroMax 题目求解问题

题目描述

给定来自CodingBat平台的zeroMax题目,规则如下:

返回给定数组的调整版本,将数组中的每个零值替换为该零值右侧位置的最大奇数;若零值右侧不存在奇数值,则保留该零值不变。

题目示例

zeroMax([0, 5, 0, 3]) → [5, 5, 3, 3]
zeroMax([0, 4, 0, 3]) → [3, 4, 3, 3]
zeroMax([0, 1, 0]) → [1, 1, 0]

现有实现

以下循环写法的解题代码已通过CodingBat平台的全部测试用例:

public int[] zeroMax(int[] nums) {
  boolean containsZero = java.util.stream.IntStream.of(nums).anyMatch(x -> x == 0);
  if (!containsZero) {
    return nums;
  }
  
  int[] zeroMax = new int[nums.length];
  int largestOddRight = 0;
  
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 0) {
      for (int j = i+1; j < nums.length; j++) {
        if (nums[j] % 2 != 0) {
          if (nums[j] > largestOddRight) {
            largestOddRight = nums[j];
          }
        }
      }
      zeroMax[i] = largestOddRight;
      largestOddRight = 0;
    } else {
      zeroMax[i] = nums[i];
    }
    
  }
  
  return zeroMax;
}

待解决问题

如何使用Stream API完成该题目的求解?

测试通过结果截图


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 17:51:23