第二章 最大子序列和、二分法查找、辗转相除法
2016-07-12 10:52
357 查看
1,最大子序列和(最优解)
求出数组中最大的子序列的和,如下:input : int[] a = {-2, 11, -4, 13, -5, -2};
syso : 20
void maxSum(int[] a){ int maxSum = 0; int thisSum = 0; for(int i = 0; i < a.length; i++){ thisSum += a[i]; thisSum = thisSum < 0 ? 0 : thisSum; maxSum = thisSum > maxSum ? thisSum : maxSum; } System.out.print(maxSum); }
2,二分法查找。
场景:有序数组快速查找数位置。递归
/** * param a is array * param x is will searched element */ void search(int[] a, int x){ System.out.print(x + " 位置为:" + binarySearch(a, x, 0, a.length-1)); } int binarySearch(int[] a, int x, int left, int right){ int mid = (left + right)/2; if(x < a[mid]){ return this.binarySearch(a, x, left, mid - 1); }else if(x > a[mid]){ return this.binarySearch(a, x, mid + 1, right); }else{ return mid; } return -1; }
非递归
int binarySearch(int[] a, int x){ int start = 0; int end = a.length; int mid = (start + end)/2 while(start <= end){ if(x < a[mid]){ end = mid -1; }else if(x > a[mid]){ start = mid + 1; }else{ return mid; } } return -1; }
3,辗转相除法(欧几里得算法)
辗转相除法:a,b的最大公因数 x,a/b = c …… r1,b/r1 = d …….r2, ….. r2==0, x = r1。
int getMaxFactor(int a, int b){ // a = maxNumber, b = minNumber if(a < b){ int temp = a; a = b; b = temp; }else if(a == b){ return 1; } while(b != 0){ int c = a % b; a = b; b = c; } return a; }
以上内容均是很简单的基础代码,至于为什么总结出来,是因为要养成一个良好的写博客习惯,而且很多事都是慢活,不可以心急。第一次使用mackdown,花费了我不少时间,但是最终写出的文章格式还是很美观的。加油!送给自己。
相关文章推荐
- CodeForces 254C 字典序
- 读书笔记-现代操作系统-3储存管理-3.6有关实现的问题
- Java开发中的23种设计模式详解
- FZU 2082 树链剖分
- 构建微服务:Spring boot 入门篇
- logstash使用
- linux用户相关及/etc/passed,/etc/group,/etc/shadow
- Eclipse中 Linked Resources 的使用
- org.springframework.web.context.ContextLoaderListener
- 文字 AnimatedOpeningType css3的文字3D翻转特效
- 发送彩信需要先通过彩信猫拨号连上GPRS网络
- GSM蜂窝基站定位基本原理浅析
- 手机定位技术简谈
- 基站id转GPS经纬度
- 基站定位 CellTrack
- python 学习第二篇 排序
- Hibernate关联映射(3) 2016-07-12
- 手机定位原理
- 多普达P800硬启动的方法
- Windows Mobile 6 模拟器上网设置