我试图让节目接近The Maximum Volume of Trapped Rain Water in 3D。该计划必须输出下雨后捕获的水量。 假设输入是[0,1,0,2,1,0,1,3,2,1,2,1]
http://i.stack.imgur.com/mbX7I.png
输出应为6
我已经在我的代码中实现了他的算法,并且我在评论中提到了1个错误,说明"无法解决方法max(int,double)"。
任何人都可以解释我如何解决它?我对java很新。谢谢。
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int[] numbers = new int[10];
Main obj = new Main();
System.out.println("Enter 10 numbers");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = scn.nextInt();
}
System.out.println("Numbers entered: ");
obj.output(numbers);
int min = Arrays.stream(numbers).min().getAsInt();
int max = Arrays.stream(numbers).max().getAsInt();
System.out.println("Min = " + min);
System.out.println("Max = " + max);
System.out.println("Second max = " + obj.secondHighest(numbers));
}
public void output(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
public int secondHighest(int[] numbers) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : numbers) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
int trapWaterVolume(int[] numbers) {
int n = numbers.length;
int[] leftmost = new int[n];
int[] rightmost = new int[n];
int leftMaxSoFar = 0;
for (int i = 0; i < n; i++) {
leftmost[i] = leftMaxSoFar;
if (numbers[i] > leftMaxSoFar) leftMaxSoFar = numbers[i];
}
//right exclusive scan, O(n), the highest bar to the right each point
int rightMaxSoFar = 0;
for (int i = n - 1; i >= 0; i--){
rightmost[i] = rightMaxSoFar;
if (numbers[i] > rightMaxSoFar) rightMaxSoFar = numbers[i];
}
// Summation, O(n)
int vol = 0;
for (int i = 0; i < n; i++){
vol += max(0, min(leftmost[i], (rightmost[i]) - (numbers[i]))); //Error @max
// can't resolve method max(int, double)
}
return vol;
}
}
答案 0 :(得分:0)
使用Math.max
代替max
,因为您尚未声明max方法,但Math类中已有一个。
vol += Math.max(0, min(leftmost[i], (rightmost[i]) - (numbers[i])));