簡體   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