算法经典面试题整理(java实现)

以下从Java角度解释面试常见的算法和数据结构:字符串,链表,树,图,排序,递归 vs. 迭代,动态规划,位操作,概率问题,排列组合,以及一些需要寻找规律的题目。

1. 字符串和数组

字符串和数组是最常见的面试题目类型,应当分配最大的时间。

关于字符串,首先需要注意的是和C++不同,Java字符串不是char数组。没有IDE代码自动补全功能,应该记住下面的这些常用的方法。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. toCharArray() //获得字符串对应的char数组  
  2. Arrays.sort()  //数组排序  
  3. Arrays.toString(char[] a) //数组转成字符串  
  4. charAt(int x) //获得某个索引处的字符  
  5. length() //字符串长度  
  6. length //数组大小  
  7. substring(int beginIndex)   
  8. substring(int beginIndex, int endIndex)  
  9. Integer.valueOf() //string to integer  
  10. String.valueOf() /integer to string  

字符串和数组本身很简单,但是相关的题目需要更复杂的算法来解决。比如说动态规划,搜索,等等。

经典题目:
0) Rotate Array
1) Evaluate Reverse Polish Notation (Stack)
2) Longest Palindromic Substring (DP)
3) Word Break (DP)
3) Word Break II (DP, DFS)
4) Word Ladder (Queue, BFS)
5) Median of Two Sorted Arrays
6) Regular Expression Matching
7) Merge Intervals
8) Insert Interval
9) Two Sum
9) Two Sum II – Input array is sorted
9) Two Sum III - Data structure design
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 [Palantir]
22) Triangle
23) Distinct Subsequences Total
24) Maximum Subarray [Palantir, LinkedIn]
24) Maximum Product Subarray [LinkedIn]
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 [Google]
29) Palindrome Partitioning
29) Palindrome Partitioning II 
30) Reverse Words in a String 
31) Find Minimum in Rotated Sorted Array 
31) Find Minimum in Rotated Sorted Array II
32) Find Peak Element
33) Min Stack
34) Majority Element
35) Combination Sum (DFS)
35) Combination Sum II (DFS)
36) Best Time to Buy and Sell Stock 
36) Best Time to Buy and Sell Stock II
36) Best Time to Buy and Sell Stock III (DP)
36) Best Time to Buy and Sell Stock IV (DP)
37) Longest Common Prefix [Google]
38) Largest Number
39) Combinations (DFS)
40) Compare Version Numbers
41) Gas Station
42) Candy [Google]
43) Jump Game
44) Pascal's Triangle
44) Pascal’s Triangle II 
45) Container With Most Water
46) Count and Say
47) Repeated DNA Sequences
48) House Robber 
49) Dungeon Game (DP) 
50) Number of Islands (DFS/BFS)
51) Surrounded Regions (BFS)
52) Max Points on a Line
53) Letter Combinations of a Phone Number (DFS)
54) Remove Element 
55) Anagrams
56) Search for a Range
57) Simplify Path
58) Isomorphic Strings
59) Minimum Size Subarray Sum
60) Minimum Path Sum (DP)
61) Unique Paths (DP)

2. 链表

在Java中,链表的实现非常简单,每个节点Node都有一个值val和指向下个节点的链接next。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class Node {  
  2.     int val;  
  3.     Node next;  
  4.    
  5.     Node(int x) {  
  6.         val = x;  
  7.         next = null;  
  8.     }  
  9. }  


链表两个著名的应用是栈Stack和队列Queue。在Java标准库都都有实现,一个是Stack,另一个是LinkedList(Queue是它实现的接口)。

经典题目:

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
10) Intersection of Two Linked Lists
11) Remove Linked List Elements
12) Swap Nodes in Pairs
13) Reverse Linked List

3. 树

这里的树通常是指二叉树,每个节点都包含一个左孩子节点和右孩子节点,像下面这样:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class TreeNode{  
  2.     int value;  
  3.     TreeNode left;  
  4.     TreeNode right;  
  5. }  

下面是与树相关的一些概念:

二叉搜索树:左结点 <= 中结点 <= 右结点
平衡 vs. 非平衡:平衡二叉树中,每个节点的左右子树的深度相差至多为1(1或0)。
满二叉树(Full Binary Tree):除叶子节点以为的每个节点都有两个孩子。
完美二叉树(Perfect Binary Tree):是具有下列性质的满二叉树:所有的叶子节点都有相同的深度或处在同一层次,且每个父节点都必须有两个孩子。
完全二叉树(Complete Binary Tree):二叉树中,可能除了最后一个,每一层都被完全填满,且所有节点都必须尽可能想左靠。

经典题目:

1) Binary Tree Preorder Traversal 
2) Binary Tree Inorder Traversal [Palantir]
3) Binary Tree Postorder Traversal
4) Binary Tree Level Order Traversal
4) Binary Tree Level Order Traversal II
5) Validate Binary Search Tree
6) Flatten Binary Tree to Linked List
7) Path Sum (DFS or BFS)
7) Path Sum II (DFS) 
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
14) Symmetric Tree
15) Binary Search Tree Iterator 
16) Binary Tree Right Side View
17) Implement Trie (Prefix Tree)
18) Add and Search Word - Data structure design (DFS)

4. 图

图相关的问题主要集中在深度优先搜索(depth first search)和广度优先搜索(breath first search)。深度优先搜索很简单,广度优先要注意使用queue. 下面是一个简单的用队列Queue实现广度优先搜索。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class GraphTest {  
  2.     public static void breathFirstSearch(GraphNode root, int x){  
  3.         if(root.val == x)  
  4.             System.out.println("find in root");  
  5.    
  6.         Queue queue = new Queue();  
  7.         root.visited = true;  
  8.         queue.enqueue(root);  
  9.    
  10.         while(queue.first != null){  
  11.             GraphNode c = (GraphNode) queue.dequeue();  
  12.             for(GraphNode n: c.neighbors){  
  13.    
  14.                 if(!n.visited){  
  15.                     System.out.print(n + " ");  
  16.                     n.visited = true;  
  17.                     if(n.val == x)  
  18.                         System.out.println("Find "+n);  
  19.                     queue.enqueue(n);  
  20.                 }  
  21.             }  
  22.         }  
  23.     }  
  24. }  


经典题目:

1) Clone Graph
2) Course Schedule (DFS/BFS)

5. 排序

下面是不同排序算法的时间复杂度,你可以去wiki看一下这些算法的基本思想。

AlgorithmAverage TimeWorst TimeSpace
冒泡排序(Bubble sort)n^2n^21
选择排序(Selection sort)n^2n^21
插入排序(Insertion sort)n^2n^2 
快速排序(Quick sort)n log(n)n^2 
归并排序(Merge sort)n log(n)n log(n)depends

* 另外还有BinSort, RadixSort和CountSort 三种比较特殊的排序。

经典题目:

1) Mergesort
2) Quicksort
3) InsertionSort.
4) Maximum Gap (Bucket Sort)

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;

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public static int f(int n){  
  2.     if(n <= 2return n;  
  3.     int x = f(n-1) + f(n-2);  
  4.     return x;  
  5. }  

递归方法的时间复杂度是指数级,因为有很多冗余的计算:

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)

直接的想法是将递归转换为迭代:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public static int f(int n) {  
  2.     if (n <= 2){  
  3.         return n;  
  4.     }  
  5.    
  6.     int first = 1, second = 2;  
  7.     int third = 0;  
  8.     for (int i = 3; i <= n; i++) {  
  9.         third = first + second;  
  10.         first = second;  
  11.         second = third;  
  12.     }  
  13.     return third;  
  14. }  


这个例子迭代花费的时间更少,你可能复习一个两者的区别Recursion vs Iteration

7. 动态规划

动态规划是解决下面这些性质类问题的技术:

  1. 一个问题可以通过更小子问题的解决方法来解决,或者说问题的最优解包含了其子问题的最优解
  2. 有些子问题的解可能需要计算多次
  3. 子问题的解存储在一张表格里,这样每个子问题只用计算一次
  4. 需要额外的空间以节省时间

爬台阶问题完全符合上面的四条性质,因此可以用动态规划法来解决。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public static int[] A = new int[100];  
  2.    
  3. public static int f3(int n) {  
  4.     if (n <= 2)  
  5.         A[n]= n;  
  6.    
  7.     if(A[n] > 0)  
  8.         return A[n];  
  9.     else  
  10.         A[n] = f3(n-1) + f3(n-2);//store results so only calculate once!  
  11.     return A[n];  
  12. }  


经典题目:

1) Edit Distance
2) Longest Palindromic Substring
3) Word Break
3) Word Break II
4) Maximum Subarray
4) Maximum Product Subarray
5) Palindrome Partitioning
5) Palindrome Partitioning II 
6) Candy [Google]
7) Jump Game
8) Best Time to Buy and Sell Stock III (DP)
8) Best Time to Buy and Sell Stock IV (DP)
9) Dungeon Game (DP) 
10) Minimum Path Sum (DP)
11) Unique Paths (DP)

8. 位操作

常用位操作符:

OR (|)AND (&)XOR (^)Left Shift (<<)Right Shift (>>)Not (~)
1|0=11&0=01^0=10010<<2=10001100>>2=0011~1=0

用一个题目来理解这些操作 -

获得给定数字n的第i位:(i从0计数并从右边开始)

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public static boolean getBit(int num, int i){  
  2.     int result = num & (1<<i);  
  3.    
  4.     return (result == 0);  
  5. }  


例如,获得数字10的第2位:

i=1, n=10
1<<1= 10
1010&10=10
10 is not 0, so return true;

经典题目:

1) Single Number
1) Single Number II
2) Maximum Binary Gap
3) Number of 1 Bits 
4) Reverse Bits 
5) Repeated DNA Sequences
6) Bitwise AND of Numbers Range

9. 概率问题

解决概率相关的问题通常需要先分析问题,下面是一个这类问题的简单例子:

一个房间里有50个人,那么至少有两个人生日相同的概率是多少?(忽略闰年的事实,也就是一年365天)

计算某些事情的概率很多时候都可以转换成先计算其相对面。在这个例子里,我们可以计算所有人生日都互不相同的概率,也就是:365/365 * 364/365 * 363/365 * … * (365-49)/365,这样至少两个人生日相同的概率就是1 – 这个值。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public static double caculateProbability(int n){  
  2.     double x = 1;   
  3.    
  4.     for(int i=0; i<n; i++){  
  5.         x *=  (365.0-i)/365.0;  
  6.     }  
  7.    
  8.     double pro = Math.round((1-x) * 100);  
  9.     return pro/100;  
  10. }  


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
4) Generate Parentheses

11. 其他类型的题目

主要是不能归到上面10大类的。需要寻找规律,然后解决问题的。

经典题目:

1) Reverse Integer
2) Palindrome Number
3) Pow(x,n)
4) Subsets
5) Subsets II
6) Fraction to Recurring Decimal [Google]
7) Excel Sheet Column Number
8) Excel Sheet Column Title 
9) Factorial Trailing Zeroes
10) Happy Number

11) Count Primes

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值