以下从Java的角度总结了面试常见的算法和数据结构:字符串,链表,树,图,排序,递归 vs. 迭代,动态规划,位操作,概率问题,排列组合,以及一些需要寻找规律的题目。
1. 字符串、数组和矩阵
首先需要注意的是和C++不同,Java字符串不是char数组。没有IDE代码自动补全功能,应该记住下面这些常用的方法。
toCharArray()//获得字符串对应的char数组
Arrays.sort() //数组排序
Arrays.toString(char[] a)//数组转成字符串
charAt(intx)//获得某个索引处的字符
length() //字符串长度
length //数组大小
substring(intbeginIndex)
substring(intbeginIndex,intendIndex)
Integer.valueOf() //string to integer
String.valueOf() //integer to string
字符串和数组本身很简单,但是相关的题目需要更复杂的算法来解决。比如说动态规划,搜索等。
2. 链表
在Java中,链表的实现非常简单,每个节点Node都有一个值val和指向下个节点的链接next。
classNode {
intval;
Node next;
Node(intx) {
val = x;
next = null;
}
}
链表两个著名的应用是栈Stack和队列Queue。在Java标准库中都有实现,一个是Stack,另一个是LinkedList(Queue是它实现的接口)。
Stack
classStack{
Node top;
publicNode peek(){
if(top !=null){
returntop;
}
returnnull;
}
publicNode pop(){
if(top ==null){
returnnull;
}else{
Node temp = newNode(top.val);
top = top.next;
returntemp;
}
}
publicvoidpush(Node n){
if(n !=null){
n.next = top;
top = n;
}
}
}
Queue
classQueue{
Node first, last;
publicvoidenqueue(Node n){
if(first ==null){
first = n;
last = first;
}else{
last.next = n;
last = n;
}
}
publicNode dequeue(){
if(first ==null){
returnnull;
}else{
Node temp = newNode(first.val);
first = first.next;
returntemp;
}
}
}
3. 树和堆
这里的树通常是指二叉树,每个节点都包含一个左孩子节点和右孩子节点,如下所示:
classTreeNode{
intvalue;
TreeNode left;
TreeNode right;
}
下面是与树相关的一些概念:
二叉搜索树:左结点 <= 中结点 <= 右结点
平衡 vs. 非平衡:平衡二叉树中,每个节点的左右子树的深度相差至多为1(1或0)。
满二叉树(Full Binary Tree):除叶子节点以外的每个节点都有两个孩子。
完美二叉树(Perfect Binary Tree):是具有下列性质的满二叉树:所有的叶子节点都有相同的深度或处在同一层次,且每个父节点都必须有两个孩子。
完全二叉树(Complete Binary Tree):二叉树中,可能除了最后一层,每一层都被完全填满,且所有节点都必须尽可能向左靠。
堆是一种特殊的基于树的数据结构,满足堆属性。其操作的时间复杂度是很重要的(例如查找最小,删除最小,插入等)。在Java中,知道PriorityQueue很重要。
4. 图
图相关的问题主要集中在深度优先搜索(depth first search)和广度优先搜索(breath first search)。深度优先搜索很简单,广度优先要注意使用queue存储节点。下面是一个简单的用队列Queue实现的广度优先搜索。
1) 定义图节点
classGraphNode{
intval;
GraphNode next;
GraphNode[] neighbors;
booleanvisited;
GraphNode(intx) {
val = x;
}
GraphNode(intx, GraphNode[] n){
val = x;
neighbors = n;
}
publicString toString(){
return"value: "+this.val;
}
}
2) 定义Queue
classQueue{
GraphNode first, last;
publicvoidenqueue(GraphNode n){
if(first ==null){
first = n;
last = first;
}else{
last.next = n;
last = n;
}
}
publicGraphNode dequeue(){
if(first ==null){
returnnull;
}else{
GraphNode temp = newGraphNode(first.val,
first.neighbors);
first = first.next;
returntemp;
}
}
}
3) 使用Queue的BFS
publicclassGraphTest {
publicstaticvoidmain(String[] args) {
GraphNode n1 = newGraphNode(1);
GraphNode n2 = newGraphNode(2);
GraphNode n3 = newGraphNode(3);
GraphNode n4 = newGraphNode(4);
GraphNode n5 = newGraphNode(5);
n1.neighbors = newGraphNode[]{n2,n3,n5};
n2.neighbors = newGraphNode[]{n1,n4};
n3.neighbors = newGraphNode[]{n1,n4,n5};
n4.neighbors = newGraphNode[]{n2,n3,n5};
n5.neighbors = newGraphNode[]{n1,n3,n4};
breathFirstSearch(n1, 5);
}
publicstaticvoidbreathFirstSearch(GraphNode root,intx){
if(root.val == x)
System.out.println("find in root");
Queue queue = newQueue();
root.visited = true;
queue.enqueue(root);
while(queue.first !=null){
GraphNode c = (GraphNode) queue.dequeue();
for(GraphNode n: c.neighbors){
if(!n.visited){
System.out.print(n + " ");
n.visited = true;
if(n.val == x)
System.out.println("Find "+n);
queue.enqueue(n);
}
}
}
}
}
输出:
value: 2 value: 3 value: 5 Find value: 5
value: 4
5. 排序
下面是不同排序算法的时间复杂度,你可以去维基上看一下这些算法的基本思想。
算法
平均时间复杂度
最坏时间复杂度
辅助空间
冒泡排序(Bubble sort)
n^2
n^2
1
选择排序(Selection sort)
n^2
n^2
1
插入排序(Insertion sort)
n^2
n^2
快速排序(Quick sort)
n log(n)
n^2
归并排序(Merge sort)
n log(n)
n log(n)
depends
* 另外还有BinSort, RadixSort和CountSort 三种比较特殊的排序。
6. 递归 vs. 迭代
对程序员来说,递归应该是一个与生俱来的思想(a built-in thought),可以通过一个简单的例子来说明。
问题:
有n步台阶,一次只能上1步或2步,共有多少种走法。
步骤1:找到走完前n步台阶和前n-1步台阶之间的关系。
为了走完n步台阶,只有两种方法:从n-1步台阶爬1步走到或从n-2步台阶处爬2步走到。如果f(n)是爬到第n步台阶的方法数,那么f(n) = f(n-1) + f(n-2)。
步骤2:确保开始条件是正确的。
f(0) = 0;
f(1) = 1;
publicstaticintf(intn){
if(n <=2)returnn;
intx = f(n-1) + f(n-2);
returnx;
}
递归方法的时间复杂度是指数级的,因为有很多冗余的计算:
f(5)
f(4) + f(3)
f(3) + f(2) + f(2) + f(1)
f(2) + f(1) + f(1) + f(0) + f(1) + f(0) + f(1)
f(1) + f(0) + f(1) + f(1) + f(0) + f(1) + f(0) + f(1)
直接的想法是将递归转换为迭代:
publicstaticintf(intn) {
if(n <=2){
returnn;
}
intfirst =1, second =2;
intthird =0;
for(inti =3; i <= n; i++) {
third = first + second;
first = second;
second = third;
}
returnthird;
}
这个例子迭代花费的时间更少,你可能想看看两者的区别 Recursion vs Iteration。
7. 动态规划
动态规划是解决具有下面这些性质问题的技术:
一个问题可以通过解决更小子问题来解决,或者说问题的最优解包含了其子问题的最优解
有些子问题的解可能需要计算多次
子问题的解存储在一张表格里,这样每个子问题只需计算一次
需要额外的空间以节省时间
爬台阶问题完全符合上面的四条性质,因此可以用动态规划法来解决。
publicstaticint[] A =newint[100];
publicstaticintf3(intn) {
if(n <=2)
A[n]= n;
if(A[n] >0)
returnA[n];
else
A[n] = f3(n-1) + f3(n-2);//存储结果,只计算一次!
returnA[n];
}
经典题目:
8. 位操作
常用位操作符:
OR (|)
AND (&)
XOR (^)
Left Shift (<
Right Shift (>>)
Not (~)
1|0=1
1&0=0
1^0=1
0010<<2=1000
1100>>2=0011
~1=0
用一个题目来理解这些操作:获得给定数字n的第i位:(i从0计数并从右边开始)
publicstaticbooleangetBit(intnum,inti){
intresult = num & (1<
if(result ==0){
returnfalse;
}else{
returntrue;
}
例如,获得数字10的第2位:
i=1, n=10
1<<1= 10
1010&10=10
10 is not 0, so return true;
9. 概率问题
解决概率相关的问题通常需要先分析问题,下面是一个简单的例子:
一个房间里有50个人,那么至少有两个人生日相同的概率是多少?(忽略闰年的事实,也就是一年365天)
计算某些事情的概率很多时候都可以转换成先计算其相对面。在这个例子里,我们可以计算所有人生日都互不相同的概率,也就是:365/365 * 364/365 * 363/365 * … * (365-49)/365,这样至少两个人生日相同的概率就是1 – 这个值。
publicstaticdoublecaculateProbability(intn){
doublex =1;
for(inti=0; i
x *= (365.0-i)/365.0;
}
doublepro = Math.round((1-x) *100);
returnpro/100;
}
calculateProbability(50) = 0.97
经典题目:桶中取球
10. 排列组合
组合和排列的区别在于次序是否关键。
例1:
1、2、3、4、5这5个数字,用java写一个方法,打印出所有不同的排列, 如:51234、41235等。要求:"4″不能在第三位,"3″与”5″不能相连。
例2:
5个香蕉,4个梨子,3个苹果。同一种水果都是一样的,这些水果有多少种不同的组合情况。
经典问题:
11. 其他类型的题目
主要是不能归到上面10大类的。需要寻找规律,然后解决问题。
经典题目:
参考/推荐的资料:
1. Binary tree
2. Introduction to Dynamic Programming
3. UTSA Dynamic Programming slides
4. Birthday paradox
5. Cracking the Coding Interview: 150 Programming InterviewQuestions and Solutions, Gayle Laakmann McDowell
6. Counting sort
7. LeetCode Online Judge