算法小题目

一:求GCG(greatest common divisor)
analysis: tow nonnegative integer p and q, if q is 0 then gcd is q, then the gcd is the greatest common divisor of q and p%q. q和p%q的最大公约数,当然也是p和q的最大公约数。

int gcd(int p, int q){
if(q == 0) return q;
return gcd(q, p%q);
}


二:merge two sorted integer array into a third array, and make sure the third array also be sorted.
analysis: image two integer array are a and b, create array c and its length is
a.lenght plus b.length, define two varible indexA, indexB pointing the index of a and b, then loop infinite comparing a[indexA] and b[indexB], if a[indexA] > b[indexB], then assign b[indexB] to c[indexA+indexB] and indexB increase by 1, so vice verse. if indexA exceeds a.length or indexB exceeds b.length, then copy the remaining of a or b to c and terminates the loop.
pseudo code:

int[] a = {};
int[] b = {};
int[] c = new int[a.length+b.length];
int indexA = indexB = 0;
while(true){
while(true){
if(indexA == a.length){// copy remaining b to c
System.arraycopy(b, indexB, c, indexA+indexB, b.length - indexB);
break;
}
if(indexB == b.length){//copy remaining a to c
System.arraycopy(a, indexA, c, indexA+indexB, a.length-indexA);
break;
}

if(a[indexA] > b[indexB]){
c[indexA+indexB] = b[indexB];
indexB++;
}else{
c[indexA+indexB] = a[indexA];
indexA++;
}
}
}


三:reverse an array or testify if a number is a palindrome number
pseudo code:

int[] a = {};
int tmp;
for(int i=0;i<a.length/2;i++){
tmp = a[i];
a[i] = a[a.length-1-i];
a[a.length-1-i] = tmp;
}


四:matrix-matrix multiplicatoin
在计算机中,一个矩阵说穿了就是一个二维数组。一个n行m列的矩阵可以乘以一个m行p列的矩阵,得到的结果是一个n行p列的矩阵,其中的第i行第j列位置上的数等于前一个矩阵第i行上的m个数与后一个矩阵第j列上的m个数对应相乘后所有m个乘积的和
pseudo code:

int[][] a = {{1, 1},{2, 0}};
int[][] b = {{0, 2, 3}, {1, 1, 2}};
if(a[0].length != b.length){
throw new IllegalArgumentException("first matrix's column length must equals with second matrix's row length");
}
int[][] c = new int[a.length][b[0].length];
for(int i=0;i<a.length;i++){//matrix a's row loop
for(int j=0;j<b[0].length;j++){//matrix b's column loop
for(int k=0;k<a[0].length;k++){
c[i][j] += a[i][k] * b[k][j];
}
}
}


五:HanoiTower
思想:首先要把前N-1个盘子转移到辅助柱,然后把第N个盘转到目标柱,最后再把前N-1个盘从辅助柱转移到目标柱,在转移过程中,把第三根柱子视为辅助柱。
pseudo code:

private static void hanoTower(String start, String dest, String auxiliary, int number){
if(number == 0){
return ;
}
hanoTower(start, auxiliary, dest, number-1);
count++;
System.out.println("move " + number + " from "+ start +" to "+ dest);
hanoTower(auxiliary, dest, start, number-1);
}

结论:总的移动次数是2^n -1, 如果N是偶数,则开始把1号盘移到辅助柱,如果N是奇数,把1号盘移到目标柱上。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值