天天看點

面試10大算法彙總+常見題目解答(Java)

原文位址:http://www.lilongdream.com/2014/04/10/94.html(為轉載+整理)

以下從Java的角度總結了面試常見的算法和資料結構:字元串,連結清單,樹,圖,排序,遞歸 vs. 疊代,動态規劃,位操作,機率問題,排列組合,以及一些需要尋找規律的題目。

1. 字元串、數組和矩陣

首先需要注意的是和C++不同,Java字元串不是char數組。沒有IDE代碼自動補全功能,應該記住下面這些常用的方法。

toCharArray()  //獲得字元串對應的char數組
Arrays.sort()  //數組排序
Arrays.toString(char[] a) //數組轉成字元串
charAt(int x)  //獲得某個索引處的字元
length()       //字元串長度
length         //數組大小
substring(int beginIndex) 
substring(int beginIndex, int endIndex)
Integer.valueOf() //string to integer
String.valueOf()  //integer to string
           

字元串和數組本身很簡單,但是相關的題目需要更複雜的算法來解決。比如說動态規劃,搜尋等。

經典題目:

1) Evaluate Reverse Polish Notation

2) Longest Palindromic Substring

3) Word Break

4) Word Ladder

5) Median of Two Sorted Arrays

6) Regular Expression Matching

7) Merge Intervals

8) Insert Interval

9) Two Sum

9) 3Sum

9) 4Sum

10) 3Sum Closest

11) String to Integer

12) Merge Sorted Array

13) Valid Parentheses

14) Implement strStr()

15) Set Matrix Zeroes

16) Search Insert Position

17) Longest Consecutive Sequence

18) Valid Palindrome

19) Spiral Matrix

20) Search a 2D Matrix

21) Rotate Image

22) Triangle

23) Distinct Subsequences Total

24) Maximum Subarray

25) Remove Duplicates from Sorted Array

26) Remove Duplicates from Sorted Array II

27) Longest Substring Without Repeating Characters

28) Longest Substring that contains 2 unique characters

29) Palindrome Partitioning

2. 連結清單

在Java中,連結清單的實作非常簡單,每個節點Node都有一個值val和指向下個節點的連結next。

class Node {
	int val;
	Node next;

	Node(int x) {
		val = x;
		next = null;
	}
}
           

連結清單兩個著名的應用是棧Stack和隊列Queue。在Java标準庫中都有實作,一個是Stack,另一個是LinkedList(Queue是它實作的接口)。

Stack

class Stack{
	Node top; 

	public Node peek(){
		if(top != null){
			return top;
		}

		return null;
	}

	public Node pop(){
		if(top == null){
			return null;
		}else{
			Node temp = new Node(top.val);
			top = top.next;
			return temp;	
		}
	}

	public void push(Node n){
		if(n != null){
			n.next = top;
			top = n;
		}
	}
}
           

Queue

class Queue{
	Node first, last;

	public void enqueue(Node n){
		if(first == null){
			first = n;
			last = first;
		}else{
			last.next = n;
			last = n;
		}
	}

	public Node dequeue(){
		if(first == null){
			return null;
		}else{
			Node temp = new Node(first.val);
			first = first.next;
			return temp;
		}	
	}
}
           

經典題目:

1) Add Two Numbers

2) Reorder List

3) Linked List Cycle

4) Copy List with Random Pointer

5) Merge Two Sorted Lists

6) Merge k Sorted Lists *

7) Remove Duplicates from Sorted List

8) Partition List

9) LRU Cache

3. 樹和堆

這裡的樹通常是指二叉樹,每個節點都包含一個左孩子節點和右孩子節點,如下所示:

class TreeNode{
	int value;
	TreeNode left;
	TreeNode right;
}
           

下面是與樹相關的一些概念:

二叉搜尋樹:左結點 <= 中結點 <= 右結點

平衡 vs. 非平衡:平衡二叉樹中,每個節點的左右子樹的深度相差至多為1(1或0)。

滿二叉樹(Full Binary Tree):除葉子節點以外的每個節點都有兩個孩子。

完美二叉樹(Perfect Binary Tree):是具有下列性質的滿二叉樹:所有的葉子節點都有相同的深度或處在同一層次,且每個父節點都必須有兩個孩子。

完全二叉樹(Complete Binary Tree):二叉樹中,可能除了最後一層,每一層都被完全填滿,且所有節點都必須盡可能向左靠。

堆是一種特殊的基于樹的資料結構,滿足堆屬性。其操作的時間複雜度是很重要的(例如查找最小,删除最小,插入等)。在Java中,知道PriorityQueue很重要。

經典題目:

1) Binary Tree Preorder Traversal 

2) Binary Tree Inorder Traversal

3) Binary Tree Postorder Traversal

4) Word Ladder

5) Validate Binary Search Tree

6) Flatten Binary Tree to Linked List

7) Path Sum

8) Construct Binary Tree from Inorder and Postorder Traversal

9) Convert Sorted Array to Binary Search Tree

10) Convert Sorted List to Binary Search Tree

11) Minimum Depth of Binary Tree

12) Binary Tree Maximum Path Sum *

13) Balanced Binary Tree

4. 圖

圖相關的問題主要集中在深度優先搜尋(depth first search)和廣度優先搜尋(breath first search)。深度優先搜尋很簡單,廣度優先要注意使用queue存儲節點。下面是一個簡單的用隊列Queue實作的廣度優先搜尋。

面試10大算法彙總+常見題目解答(Java)

1) 定義圖節點

class GraphNode{ 
	int val;
	GraphNode next;
	GraphNode[] neighbors;
	boolean visited;

	GraphNode(int x) {
		val = x;
	}

	GraphNode(int x, GraphNode[] n){
		val = x;
		neighbors = n;
	}

	public String toString(){
		return "value: "+ this.val; 
	}
}
           

2) 定義Queue

class Queue{
	GraphNode first, last;

	public void enqueue(GraphNode n){
		if(first == null){
			first = n;
			last = first;
		}else{
			last.next = n;
			last = n;
		}
	}

	public GraphNode dequeue(){
		if(first == null){
			return null;
		}else{
			GraphNode temp = new GraphNode(first.val, 
                                         first.neighbors);
			first = first.next;
			return temp;
		}	
	}
}
           

3) 使用Queue的BFS

public class GraphTest {

	public static void main(String[] args) {
		GraphNode n1 = new GraphNode(1); 
		GraphNode n2 = new GraphNode(2); 
		GraphNode n3 = new GraphNode(3); 
		GraphNode n4 = new GraphNode(4); 
		GraphNode n5 = new GraphNode(5); 

		n1.neighbors = new GraphNode[]{n2,n3,n5};
		n2.neighbors = new GraphNode[]{n1,n4};
		n3.neighbors = new GraphNode[]{n1,n4,n5};
		n4.neighbors = new GraphNode[]{n2,n3,n5};
		n5.neighbors = new GraphNode[]{n1,n3,n4};

		breathFirstSearch(n1, 5);
	}

	public static void breathFirstSearch(GraphNode root, int x){
		if(root.val == x)
			System.out.println("find in root");

		Queue queue = new Queue();
		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

經典題目:複制圖(Clone Graph)

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 三種比較特殊的排序。

(此處可見我的整理:http://www.lilongdream.com/2014/04/10/83.html)

你可能想看看 how developers sort in Java 。

經典題目:Mergesort, Quicksort, InsertionSort.

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;

public static int f(int n){
	if(n <= 2) return n;
	int x = f(n-1) + f(n-2);
	return x;
}
           

遞歸方法的時間複雜度是指數級的,因為有很多備援的計算:

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)

直接的想法是将遞歸轉換為疊代:

public static int f(int n) {

	if (n <= 2){
		return n;
	}

	int first = 1, second = 2;
	int third = 0;

	for (int i = 3; i <= n; i++) {
		third = first + second;
		first = second;
		second = third;
	}

	return third;
}
           

這個例子疊代花費的時間更少,你可能想看看兩者的差別 Recursion vs Iteration。

7. 動态規劃

動态規劃是解決具有下面這些性質問題的技術:

  1. 一個問題可以通過解決更小子問題來解決,或者說問題的最優解包含了其子問題的最優解
  2. 有些子問題的解可能需要計算多次
  3. 子問題的解存儲在一張表格裡,這樣每個子問題隻需計算一次
  4. 需要額外的空間以節省時間

爬台階問題完全符合上面的四條性質,是以可以用動态規劃法來解決。

public static int[] A = new int[100];

public static int f3(int n) {
	if (n <= 2)
		A[n]= n;

	if(A[n] > 0)
		return A[n];
	else
		A[n] = f3(n-1) + f3(n-2); //存儲結果,隻計算一次!
	return A[n];
}
           

經典題目:

1) Edit Distance

2) Longest Palindromic Substring

3) Word Break

4) Maximum Subarray

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計數并從右邊開始)

public static boolean getBit(int num, int i){
	int result = num & (1<<i);

	if(result == 0){
		return false;
	}else{
		return true;
}
           

例如,獲得數字10的第2位:

i=1, n=10

1<<1= 10

1010&10=10

10 is not 0, so return true; 經典問題:

1) Find Single Number

2) Maximum Binary Gap

9. 機率問題

解決機率相關的問題通常需要先分析問題,下面是一個簡單的例子:

一個房間裡有50個人,那麼至少有兩個人生日相同的機率是多少?(忽略閏年的事實,也就是一年365天)

計算某些事情的機率很多時候都可以轉換成先計算其相對面。在這個例子裡,我們可以計算所有人生日都互不相同的機率,也就是:365/365 * 364/365 * 363/365 * … * (365-49)/365,這樣至少兩個人生日相同的機率就是1 – 這個值。

public static double caculateProbability(int n){
	double x = 1; 

	for(int i=0; i<n; i++){
		x *=  (365.0-i)/365.0;
	}

	double pro = Math.round((1-x) * 100);
	return pro/100;
}
           

calculateProbability(50) = 0.97

經典題目:桶中取球

10. 排列組合

組合和排列的差別在于次序是否關鍵。

例1:

1、2、3、4、5這5個數字,用java寫一個方法,列印出所有不同的排列, 如:51234、41235等。要求:"4″不能在第三位,"3″與”5″不能相連。

例2:

5個香蕉,4個梨子,3個蘋果。同一種水果都是一樣的,這些水果有多少種不同的組合情況。

經典問題:

1) Permutations

2) Permutations II 

3) Permutation Sequence

11. 其他類型的題目

主要是不能歸到上面10大類的。需要尋找規律,然後解決問題。

經典題目:

1) Reverse Integer

2) Palindrome Number

3) Pow(x,n)

4) Subsets

5) Subsets II

參考/推薦的資料:

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