/**
* 给定一个数组,求出该数组的蓄水数(10分)
比如数组是 [2,1,2],那么中间1这个位置就能蓄水1
比如数组是 [3,1,2,3] , 那么中间这个1,2这个位置分别蓄水2和1,所以总蓄水数是 3
现在给定数组:
[7,2,3,9,4,7,3,8]
求出这个数组的蓄水数。
* @ClassName Test7
* @Description
* @author rk
*/
public class Test7 {
//最大值
public static int max(int[] array){
if(array.length == 0){
return 0;
}else{
int max = array[0];
for(int a : array){
if(max < a){
max = a;
}
}
return max;
}
}
//最小值
public static int min(int[] array){
if(array.length == 0){
return 0;
}else{
int min = array[0];
for(int a : array){
if(min > a){
min = a;
}
}
return min;
}
}
//蓄水量
public static int total(int[] arr){
int max = max(arr);
int min = min(arr);
int total = 0;
int[] temp = new int[arr.length];
for(int i = min; i < max; i++){
for(int j = 0; j < arr.length; j++){
if(arr[j] > i){
temp[j] = 1;
}else{
temp[j] = 0;
}
}
total += getWater(temp);
}
return total;
}
//获取临时数组中的和
public static int getWater(int[] temp){
int sum = 0;
int i = 0;
int j = temp.length -1;
//左边第一个1
while(i<j){
if(temp[i] ==1){
break;
}
i++;
}
//右边第一个1
while(j >= i){
if(temp[j] ==1){
break;
}
j--;
}
for(int k = i+1;k<j;k++){
if(temp[k] == 0) {
sum++;
}
}
return sum;
}
public static void main(String[] args) {
// int[] array = {2,1,2};
int[] array = {7,2,3,9,4,7,3,8};
System.out.println(max(array));
System.out.println(min(array));
System.out.println(total(array));
}
}
* 给定一个数组,求出该数组的蓄水数(10分)
比如数组是 [2,1,2],那么中间1这个位置就能蓄水1
比如数组是 [3,1,2,3] , 那么中间这个1,2这个位置分别蓄水2和1,所以总蓄水数是 3
现在给定数组:
[7,2,3,9,4,7,3,8]
求出这个数组的蓄水数。
* @ClassName Test7
* @Description
* @author rk
*/
public class Test7 {
//最大值
public static int max(int[] array){
if(array.length == 0){
return 0;
}else{
int max = array[0];
for(int a : array){
if(max < a){
max = a;
}
}
return max;
}
}
//最小值
public static int min(int[] array){
if(array.length == 0){
return 0;
}else{
int min = array[0];
for(int a : array){
if(min > a){
min = a;
}
}
return min;
}
}
//蓄水量
public static int total(int[] arr){
int max = max(arr);
int min = min(arr);
int total = 0;
int[] temp = new int[arr.length];
for(int i = min; i < max; i++){
for(int j = 0; j < arr.length; j++){
if(arr[j] > i){
temp[j] = 1;
}else{
temp[j] = 0;
}
}
total += getWater(temp);
}
return total;
}
//获取临时数组中的和
public static int getWater(int[] temp){
int sum = 0;
int i = 0;
int j = temp.length -1;
//左边第一个1
while(i<j){
if(temp[i] ==1){
break;
}
i++;
}
//右边第一个1
while(j >= i){
if(temp[j] ==1){
break;
}
j--;
}
for(int k = i+1;k<j;k++){
if(temp[k] == 0) {
sum++;
}
}
return sum;
}
public static void main(String[] args) {
// int[] array = {2,1,2};
int[] array = {7,2,3,9,4,7,3,8};
System.out.println(max(array));
System.out.println(min(array));
System.out.println(total(array));
}
}