您的位置:首页 > 其它

第二章 最大子序列和、二分法查找、辗转相除法

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,花费了我不少时间,但是最终写出的文章格式还是很美观的。加油!送给自己。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: