简单注水算法


import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @version 0.1
* @author QuarterLifeForJava
* 说明:1.思路见程序下面的图
* 2.未经大量反复测试
* 3.必有更好更精简方式,你可以写的更好
*/
public class Test {

//简单测试下
public static void main(String[] args) {
int test1[] = new int[]{3,1,1,3,5,1,6,8,1,4,6,2,6};
System.out.println(core(test1));
int test2[] = new int[]{1,2,3,4,5};
System.out.println(core(test2));
int test3[] = new int[]{5,4,3,2,1};
System.out.println(core(test3));
int test4[] = new int[]{5,4,3,2,1,2,3};
System.out.println(core(test4));
int test5[] = new int[]{5,4};
System.out.println(core(test5));
int test6[] = new int[]{3,9,4,8,1,1,1,3};
System.out.println(core(test6));
}

//核心处理
public static int core(int array[]){
int capacity = 0;//容量
int temp[] = Arrays.copyOf(array, array.length);
StringBuilder sb = new StringBuilder();
if(array.length<3){
return capacity;
}else{
for (int i = 0; i < array.length; i++) {
if(i==array.length-1){
temp[array.length-1] = 0;
sb.append(temp[array.length-1]);
break;
}
if(array[i]>array[i+1]){
temp[i] = 0;//0高
}else{
temp[i] = 1;//1低
}
sb.append(temp[i]);
}
}
int length = sb.toString().length();
Pattern p = Pattern.compile("0+1+0");
Matcher m = p.matcher(sb.toString());
while(m.find()){
capacity+=calculateEach(array, m.start(), m.end()-1);
m.region(m.end()-1, length);
}
return capacity;
}

//计算每组匹配
public static int calculateEach(int array[],int start,int end){
int temp = 0;
int count = 0;
if(array[start]>=array[end]){
temp = array[end];
}else{
temp = array[start];
}
for (int i = start+1; i < end; i++) {
//特殊处理类似5,4,7,8,9的情况
count+=((temp-array[i]<=0)?0:(temp-array[i]));
}
return count;
}

}

[img]http://dl2.iteye.com/upload/attachment/0103/1354/8ca1f0d5-36e9-3cd0-9a0c-084d8f2a751a.jpg[/img]
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值