繁体   English   中英

返回子数组中的最大值

[英]Return the maximum value in subarray

我试图返回索引 idx 处的子数组中的最大值,如果索引无效或子数组为空,则返回 0。 我一直在努力通过这个测试,但我似乎做不到,我不知道代码有什么问题。

我不确定你为什么使用 2d arrays。 我想这就是为什么你不能让它工作。

这是一个适用于简单一维 arrays 的解决方案:

static int[] data = new int[] { 1, 4, 2, 3 };

public static int subsetMax(int idx) {
    if(idx >= data.length || idx < 0) {
        return 0;
    }
    int max = 0;
    
    // get the subarray from `idx` til the end of the array
    int[] subarray = Arrays.copyOfRange(data, idx, data.length);

    // for each element in the subarray:
    // check if it is greater than the previous max value
    for(int elem : subarray) {
        max = Math.max(max, elem);
    }
    return max;
}

public static void main(String[] args) {
    System.out.println(subsetMax(-1)); // 0
    System.out.println(subsetMax(0)); // 4
    System.out.println(subsetMax(1)); // 4
    System.out.println(subsetMax(2)); // 3
    System.out.println(subsetMax(3)); // 3
    System.out.println(subsetMax(4)); // 0
}

从您提供的示例中,您似乎正在返回值数组。

public static List<Integer> subsetMax(int idx) {
    if(idx >= data.length || idx < 0) {
        return 0;
    }
    int max = 0;
    
    List<Integer>max_values=new ArrayList<>();

    for(int i = 0; i < data.length; i++) {
        max = data[i][0];
       for (int j = 0; j < data[i].length; j++) {
         if(data[i][j]>max) {
                max = data[i][j];
         }
       }
       max_values.add(max);
    }

   return max_values;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM