剑指offer笔记
Posted answerhfh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指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:
以上是关于剑指offer笔记的主要内容,如果未能解决你的问题,请参考以下文章