分治法求最值
来源:互联网 发布:2016淘宝造物节曲子 编辑:程序博客网 时间:2024/06/06 21:45
package test02;public class Test01 { public static void main(String[] args) { int[] a = { 3, 4,1, 3, 22, 11, 33, 90, 1,2,12,90, 89}; int max = getMax(a, 0, a.length - 1); int min = getMin(a, 0, a.length - 1); System.out.println("最大值: " + max); System.out.println("最小值:" + min); } public static int getMax(int a[], int begin, int end) { int temp1 = 0; int temp2 = 0; if (begin == end) { return temp1 = temp2 = a[begin]; } else if (begin == end - 1) { temp1 = a[begin]; temp2 = a[end]; return temp1 > temp2 ? temp1 : temp2; } else { int mid = (begin + end) / 2; temp1 = getMax(a, begin, mid); temp2 = getMax(a, mid+1, end); return temp1 > temp2 ? temp1 : temp2; } } public static int getMin(int[] a, int begin, int end) { int temp1 = 0; int temp2 = 0; if (begin == end) { return temp1 = temp2 = a[begin]; } else if (begin == end - 1) { temp1 = a[begin]; temp2 = a[end]; return temp1 > temp2 ? temp2 : temp1; } else { int mid = (begin + end) / 2; temp1 = getMin(a, 0, mid); temp2 = getMin(a, mid+1, end); return temp1 > temp2 ? temp2 : temp1; } }}
栈结构实现
package test02;import java.util.Stack;public class Test02 { public static void main(String[] args) { int[] a = { 1, 2, 3, 5,-1,-1, 32, 12, 12,100, 43, 46, 12, 11,56 }; int max = getMax(a); int min=getMin(a); System.out.println("最大值: " + max); System.out.println("最小值: "+min); } public static int getMax(int[] a) { int temp; int max = a[0]; Stack<Integer> stack = new Stack<Integer>(); stack.push(0);//把起始点压入栈 stack.push(a.length - 1);//把结尾点压入栈 while (!stack.isEmpty()) {//当栈不为空 int high = stack.pop();//从栈中取出待分元素段的起始,终止位置 int low = stack.pop(); while (high - low > 1) { int mid = (high + low) / 2; stack.push(mid + 1); stack.push(high); high = mid;//取前半段,准备继续对分 } if (high - low == 1) { temp = (a[high] > a[low]) ? a[high] : a[low]; } else { temp = a[high]; } if (temp > max) { max = temp; } } return max; } public static int getMin(int[] a){ int temp; int min=a[0]; Stack<Integer>stack=new Stack<Integer>(); stack.push(0); stack.push(a.length-1); while(!stack.isEmpty()){ int high=stack.pop(); int low=stack.pop(); while(high-low>1){ int mid=(low+high)/2; stack.push(mid+1); stack.push(high); high=mid; } if(high-low==1){ temp=(a[high]>a[low]?a[low]:a[high]); }else{ temp=a[low]; } if(temp<min){ min=temp; } } return min; }}
阅读全文
0 0
- 分治法求最值
- 分治
- 分治
- 分治
- 分治
- 分治
- 分治
- 分治
- 分治
- 分治
- 分治
- 分治
- 树分治-点分治
- 树分治(点分治+边分治)
- 分治法
- 分治法
- 分治策略
- 分治法
- spring_HibernateTemplate(Hibernate模板)_模版设计模式
- atom配置vim
- Mac-----Mac端口映射
- Python基础-__main__
- mysql中DATE_FORMAT()和str_to_date()简介
- 分治法求最值
- leetcode :expected unqualified-id before string constant
- JAVA中的糕富帅技术
- ORACLE SQL开发where子句之case-when
- 限时免费 | UWA粉丝专享定制化福利:项目性能诊断一对一!
- Essential Studio for JavaScript发布2017 v2,扩展企业Web开发界限
- MAT使用
- 一笔画问题
- poj 2823 Sliding Window(单调队列)