剑指offer笔记


面试题1:实现singleton模式


代码实现:

public class Singleton {
private static Singleton instance = null;
private static Object syncObj = new Object();
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (syncObj) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

强烈推荐:静态构造方法

public class Singleton1{
private static Singleton1 instance = new Singleton1();
private Singleton1(){
}
public static Singleton1 getInstance(){
return instance;
}
}


面试题3:二维数组中查找




代码:

public static boolean find(int[][] arr, int rows, int columns, int number) {
boolean found = false;
if (arr == null || rows == 0 || columns == 0) {
return found;
}
int row = 0;
int column = columns - 1;
while (row < rows && column >= 0) {
if (arr[row][column] == number) {
found = true;
return found;
} else if (arr[row][column] > number) {
--column;
} else {
++row;
}
}
return found;
}


面试题4:替换空格






代码:

public static char[] replaceBlank(char[] ch) {
int originLength = 0;
int i = 0;
int numberOfBlank = 0;
while (ch[i] != '\0') {
originLength++;
if (ch[i] == ' ') {
numberOfBlank++;
}

                       i++;
}


int newLength = originLength + 2 * numberOfBlank;
if (ch.length < newLength) {
return null;
}


int indexOfOrigin = originLength - 1;
int indexOfNew = newLength - 1;
while (indexOfOrigin >= 0 && indexOfNew > indexOfOrigin) {
if (ch[indexOfOrigin] == ' ') {
ch[indexOfNew--] = '0';
ch[indexOfNew--] = '2';
ch[indexOfNew--] = '%';
} else {
ch[indexOfNew--] = ch[indexOfOrigin];
}
indexOfOrigin--;
}
return ch;
}




/**
* 合并两个有序数组A1、A2, A1有足够多的空余空间 O(n)
*/
public static int[] mergeArray(int[] a1,int a2) {
int i = 0;
int a1Length = 0;
while (a1[i++] != '\0') {
a1Length++;
}
a1Length--;
int a2Length = a2.length - 1;
int newLength = a1Length + a2Length + 1;

while (newLength >= 0) {
if (a1Length < 0 && a2Length >= 0) {
a1[newLength--] = a2[a2Length--];
continue;
}
if (a2[a2Length] >= a1[a1Length]) {
a1[newLength--] = a2[a2Length--];
} else {
a1[newLength--] = a1[a1Length--];
}
}
return a1;
}



三、高质量的代码

3.1  代码的完整性



3.1.1   第三种错误处理的方法


面试题11:数值的整数次方






                   优化:




面试题12: 




       


面试题 13:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值