我是技術搬運工,好東西當然要和大家分享啦.原文地址
第二章 面試需要的基礎知識
2. 實現 Singleton
經典實現
以下實現中,私有靜態變量被延遲化實例化,這樣做的好處是,如果沒有用到該類,那麼就不會創建該私有靜態變量,從而節約資源。這個實現在多線程環境下是不安全的,因爲多個線程能夠同時進入 if(uniqueInstance == null) 內的語句塊,那麼就會多次實例化 uniqueInstance 私有靜態變量。
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
線程不安全問題的解決方案一
只需要對 getUniqueInstance() 方法加鎖,就能讓該方法一次只能一個線程訪問,從而避免了對 uniqueInstance 變量進行多次實例化的問題。但是這樣有一個問題是一次只能一個線程進入,性能上會有一定的浪費。
public static synchronized Singleton getUniqueInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
線程不安全問題的解決方案二
不用延遲實例化,採用直接實例化。
private static Singleton uniqueInstance = new Singleton();
線程不安全問題的解決方案三
考慮第一個解決方案,它是直接對 getUniqueInstance() 方法進行加鎖,而實際上只需要對 uniqueInstance = new Singleton(); 這條語句加鎖即可。使用兩個條件語句來判斷 uniqueInstance 是否已經實例化,如果沒有實例化才需要加鎖。
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {
}
public static synchronized Singleton getUniqueInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
3. 數組中重複的數字
題目描述
在一個長度爲 n 的數組裏的所有數字都在 0 到 n-1 的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 例如,如果輸入長度爲 7 的數組 {2, 3, 1, 0, 2, 5, 3},那麼對應的輸出是第一個重複的數字 2。
解題思路
這種數組元素在 [0, n-1] 範圍內的問題,可以將值爲 i 的元素放到第 i 個位置上。
public boolean duplicate(int numbers[], int length, int[] duplication) {
for (int i = 0; i < length; i++) {
while (numbers[i] != i && numbers[i] != numbers[numbers[i]]) {
swap(numbers, i, numbers[i]);
}
if (numbers[i] != i && numbers[i] == numbers[numbers[i]]) {
duplication[0] = numbers[i];
return true;
}
}
return false;
}
private void swap(int[] numbers, int i, int j) {
int t = numbers[i];
numbers[i] = numbers[j];
numbers[j] = t;
}
4. 二維數組中的查找
題目描述
在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。
public boolean Find(int target, int [][] array) {
if (array == null || array.length == 0 || array[0].length == 0) return false;
int m = array.length, n = array[0].length;
int row = 0, col = n - 1;
while (row < m && col >= 0) {
if (target == array[row][col]) return true;
else if (target < array[row][col]) col--;
else row++;
}
return false;
}
5. 替換空格
題目描述
請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串爲 We Are Happy. 則經過替換之後的字符串爲 We%20Are%20Happy。
題目要求
以 O(1) 的空間複雜度來求解。
public String replaceSpace(StringBuffer str) {
int n = str.length();
for (int i = 0; i < n; i++) {
if (str.charAt(i) == ' ') str.append(" "); // 尾部填充兩個
}
int idxOfOriginal = n - 1;
int idxOfNew = str.length() - 1;
while (idxOfOriginal >= 0 && idxOfNew > idxOfOriginal) {
if (str.charAt(idxOfOriginal) == ' ') {
str.setCharAt(idxOfNew--, '0');
str.setCharAt(idxOfNew--, '2');
str.setCharAt(idxOfNew--, '%');
} else {
str.setCharAt(idxOfNew--, str.charAt(idxOfOriginal));
}
idxOfOriginal--;
}
return str.toString();
}
6. 從尾到頭打印鏈表
正向遍歷然後調用 Collections.reverse().
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> ret = new ArrayList<>();
while (listNode != null) {
ret.add(listNode.val);
listNode = listNode.next;
}
Collections.reverse(ret);
return ret;
}
遞歸
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> ret = new ArrayList<>();
if(listNode != null) {
ret.addAll(printListFromTailToHead(listNode.next));
ret.add(listNode.val);
}
return ret;
}
不使用庫函數,並且不使用遞歸的迭代實現,利用鏈表的頭插法爲逆序的特性。
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ListNode head = new ListNode(-1); // 頭結點
ListNode cur = listNode;
while (cur != null) {
ListNode next = cur.next;
cur.next = head.next;
head.next = cur;
cur = next;
}
ArrayList<Integer> ret = new ArrayList<>();
head = head.next;
while (head != null) {
ret.add(head.val);
head = head.next;
}
return ret;
}
7. 重建二叉樹
題目描述
根據二叉樹的前序遍歷和中序遍歷的結果,重建出該二叉樹。
public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
return reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
}
private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int[] in, int inL, int inR) {
if(preL > preR || inL > inR) return null;
TreeNode root = new TreeNode(pre[preL]);
if (preL != preR) {
int idx = inL;
while (idx <= inR && in[idx] != root.val) idx++;
int leftTreeLen = idx - inL;
root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeLen, in, inL, inL + leftTreeLen - 1);
root.right = reConstructBinaryTree(pre, preL + leftTreeLen + 1, preR, in, inL + leftTreeLen + 1, inR);
}
return root;
}
8. 二叉樹的下一個結點
題目描述
給定一個二叉樹和其中的一個結點,請找出中序遍歷順序的下一個結點並且返回。注意,樹中的結點不僅包含左右子結點,同時包含指向父結點的指針。
public TreeLinkNode GetNext(TreeLinkNode pNode) {
if (pNode == null) return null;
if (pNode.right != null) {
pNode = pNode.right;
while (pNode.left != null) pNode = pNode.left;
return pNode;
} else {
TreeLinkNode parent = pNode.next;
while (parent != null) {
if (parent.left == pNode) return parent;
pNode = pNode.next;
parent = pNode.next;
}
}
return null;
}
9. 用兩個棧實現隊列
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
10.1 斐波那契數列
private int[] fib = new int[40];
public Solution() {
fib[1] = 1;
fib[2] = 2;
for (int i = 2; i < fib.length; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
}
public int Fibonacci(int n) {
return fib[n];
}
10.2 跳臺階
public int JumpFloor(int target) {
if (target == 1) return 1;
int[] dp = new int[target];
dp[0] = 1;
dp[1] = 2;
for (int i = 2; i < dp.length; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[target - 1];
}
10.3 變態跳臺階
public int JumpFloorII(int target) {
int[] dp = new int[target];
Arrays.fill(dp, 1);
for (int i = 1; i < target; i++) {
for (int j = 0; j < i; j++) {
dp[i] += dp[j];
}
}
return dp[target - 1];
}
10.4 矩形覆蓋
題目描述
我們可以用 2*1 的小矩形橫着或者豎着去覆蓋更大的矩形。請問用 n 個 2*1 的小矩形無重疊地覆蓋一個 2*n 的大矩形,總共有多少種方法?
public int RectCover(int target) {
if (target <= 2) return target;
return RectCover(target - 1) + RectCover(target - 2);
}
11. 旋轉數組的最小數字
題目描述
把一個數組最開始的若干個元素搬到數組的末尾,我們稱之爲數組的旋轉。 輸入一個非遞減排序的數組的一個旋轉,輸出旋轉數組的最小元素。 例如數組 {3, 4, 5, 1, 2} 爲 {1, 2, 3, 4, 5} 的一個旋轉,該數組的最小值爲 1。 NOTE:給出的所有元素都大於 0,若數組大小爲 0,請返回 0。
public int minNumberInRotateArray(int[] array) {
if (array.length == 0) return 0;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) return array[i + 1];
}
return 0;
}
12. 矩陣中的路徑
題目描述
請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如 a b c e s f c s a d e e 矩陣中包含一條字符串 "bcced" 的路徑,但是矩陣中不包含 "abcb" 路徑,因爲字符串的第一個字符 b 佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。
private int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
if (rows == 0 || cols == 0) return false;
char[][] m = new char[rows][cols];
for (int i = 0, idx = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m[i][j] = matrix[idx++];
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (backtracking(m, rows, cols, str, new boolean[rows][cols], 0, i, j)) return true;
}
}
return false;
}
private boolean backtracking(char[][] m, int rows, int cols, char[] str, boolean[][] used, int path, int r, int c) {
if (path == str.length) return true;
if (r < 0 || r >= rows || c < 0 || c >= cols) return false;
if (m[r][c] != str[path]) return false;
if (used[r][c]) return false;
used[r][c] = true;
for (int i = 0; i < next.length; i++) {
if (backtracking(m, rows, cols, str, used, path + 1, r + next[i][0], c + next[i][1])) return true;
}
used[r][c] = false;
return false;
}
13. 機器人的運動範圍
題目描述
地上有一個 m 行和 n 列的方格。一個機器人從座標 0, 0 的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於 k 的格子。 例如,當 k 爲 18 時,機器人能夠進入方格(35, 37),因爲 3+5+3+7 = 18。但是,它不能進入方格(35, 38),因爲 3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
private int cnt = 0;
private int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
private int[][] digitSum;
public int movingCount(int threshold, int rows, int cols) {
initDigitSum(rows, cols);
dfs(new boolean[rows][cols], threshold, rows, cols, 0, 0);
return cnt;
}
private void dfs(boolean[][] visited, int threshold, int rows, int cols, int r, int c) {
if (r < 0 || r >= rows || c < 0 || c >= cols) return;
if (visited[r][c]) return;
visited[r][c] = true;
if (this.digitSum[r][c] > threshold) return;
this.cnt++;
for (int i = 0; i < this.next.length; i++) {
dfs(visited, threshold, rows, cols, r + next[i][0], c + next[i][1]);
}
}
private void initDigitSum(int rows, int cols) {
int[] digitSumOne = new int[Math.max(rows, cols)];
for (int i = 0; i < digitSumOne.length; i++) {
int n = i;
while (n > 0) {
digitSumOne[i] += n % 10;
n /= 10;
}
}
this.digitSum = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
this.digitSum[i][j] = digitSumOne[i] + digitSumOne[j];
}
}
}
14. 剪繩子
題目描述
把一根繩子剪成多段,並且使得每段的長度乘積最大。
解題思路
儘可能多得剪長度爲 3 的繩子,並且不允許有長度爲 1 的繩子出現,如果出現了,就從已經切好長度爲 3 的繩子中拿出一段與長度爲 1 的繩子重新組合,把它們切成兩段長度爲 2 的繩子。
int maxProductAfterCuttin(int length) {
if (length < 2) return 0;
if (length == 2) return 1;
if (length == 3) return 2;
int timesOf3 = length / 3;
if (length - timesOf3 * 3 == 1) timesOf3--;
int timesOf2 = (length - timesOf3 * 3) / 2;
return (int) (Math.pow(3, timesOf3)) * (int) (Math.pow(2, timesOf2));
}
15. 二進制中 1 的個數
public int NumberOf1(int n) {
return Integer.bitCount(n);
}
n&(n-1) 該位運算是去除 n 的位級表示中最低的那一位。例如對於二進制表示 10110100,減去 1 得到 10110011,這兩個數相與得到 10110000。
public int NumberOf1(int n) {
int cnt = 0;
while (n != 0) {
cnt++;
n &= (n - 1);
}
return cnt;
}
第三章 高質量的代碼
16. 數值的整數次方
public double Power(double base, int exponent) {
if (exponent == 0) return 1;
if (exponent == 1) return base;
boolean isNegative = false;
if (exponent < 0) {
exponent = -exponent;
isNegative = true;
}
double pow = Power(base * base, exponent / 2);
if (exponent % 2 != 0) pow = pow * base;
return isNegative ? 1 / pow : pow;
}
18. 刪除鏈表中重複的結點
public ListNode deleteDuplication(ListNode pHead) {
if (pHead == null) return null;
if (pHead.next == null) return pHead;
if (pHead.val == pHead.next.val) {
ListNode next = pHead.next;
while (next != null && pHead.val == next.val) {
next = next.next;
}
return deleteDuplication(next);
} else {
pHead.next = deleteDuplication(pHead.next);
return pHead;
}
}
19. 正則表達式匹配
題目描述
請實現一個函數用來匹配包括 '.' 和 '*' 的正則表達式。模式中的字符 '.' 表示任意一個字符,而 '*' 表示它前面的字符可以出現任意次(包含 0 次)。 在本題中,匹配是指字符串的所有字符匹配整個模式。例如,字符串 "aaa" 與模式 "a.a" 和 "ab*ac*a" 匹配,但是與 "aa.a" 和 "ab*a" 均不匹配
public boolean match(char[] str, char[] pattern) {
int n = str.length, m = pattern.length;
boolean[][] dp = new boolean[n + 1][m + 1];
dp[0][0] = true;
for (int i = 1; i <= m; i++) {
if (pattern[i - 1] == '*') dp[0][i] = dp[0][i - 2];
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (str[i - 1] == pattern[j - 1] || pattern[j - 1] == '.') dp[i][j] = dp[i - 1][j - 1];
else if (pattern[j - 1] == '*') {
if (pattern[j - 2] != str[i - 1] && pattern[j - 2] != '.') dp[i][j] = dp[i][j - 2];
else dp[i][j] = dp[i][j - 1] || dp[i][j - 2] || dp[i - 1][j];
}
}
}
return dp[n][m];
}
20. 表示數值的字符串
題目描述
請實現一個函數用來判斷字符串是否表示數值(包括整數和小數)。例如,字符串 "+100","5e2","-123","3.1416" 和 "-1E-16" 都表示數值。 但是 "12e","1a3.14","1.2.3","+-5" 和 "12e+4.3" 都不是。
public boolean isNumeric(char[] str) {
String string = String.valueOf(str);
return string.matches("[\\+-]?[0-9]*(\\.[0-9]*)?([eE][\\+-]?[0-9]+)?");
}
21. 調整數組順序使奇數位於偶數前面
時間複雜度 : O(n2)空間複雜度 : O(1)
public void reOrderArray(int[] array) {
int n = array.length;
for (int i = 0; i < n; i++) {
if (array[i] % 2 == 0) {
int nextOddIdx = i + 1;
while (nextOddIdx < n && array[nextOddIdx] % 2 == 0) nextOddIdx++;
if (nextOddIdx == n) break;
int nextOddVal = array[nextOddIdx];
for (int j = nextOddIdx; j > i; j--) {
array[j] = array[j - 1];
}
array[i] = nextOddVal;
}
}
}
時間複雜度 : O(n)空間複雜度 : O(n)
public void reOrderArray(int[] array) {
int oddCnt = 0;
for (int num : array) if (num % 2 == 1) oddCnt++;
int[] copy = array.clone();
int i = 0, j = oddCnt;
for (int num : copy) {
if (num % 2 == 1) array[i++] = num;
else array[j++] = num;
}
}
22. 鏈表中倒數第 k 個結點
public ListNode FindKthToTail(ListNode head, int k) {
if (head == null) return null;
ListNode fast, slow;
fast = slow = head;
while (fast != null && k-- > 0) fast = fast.next;
if (k > 0) return null;
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
23. 鏈表中環的入口結點
public ListNode EntryNodeOfLoop(ListNode pHead) {
if (pHead == null) return null;
ListNode slow = pHead, fast = pHead;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (slow == fast) {
fast = pHead;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
24. 反轉鏈表
public ListNode ReverseList(ListNode head) {
ListNode newList = new ListNode(-1);
while (head != null) {
ListNode next = head.next;
head.next = newList.next;
newList.next = head;
head = next;
}
return newList.next;
}
25. 合併兩個排序的鏈表
public ListNode Merge(ListNode list1, ListNode list2) {
ListNode head = new ListNode(-1);
ListNode cur = head;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
cur.next = list1;
list1 = list1.next;
} else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
if (list1 != null) cur.next = list1;
if (list2 != null) cur.next = list2;
return head.next;
}
26. 樹的子結構
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null) return false;
return isSubtree(root1, root2) || HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2);
}
private boolean isSubtree(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) return true;
if (root1 == null) return false;
if (root2 == null) return true;
if (root1.val != root2.val) return false;
return isSubtree(root1.left, root2.left) && isSubtree(root1.right, root2.right);
}
第四章 解決面試題的思路
27. 二叉樹的鏡像
public void Mirror(TreeNode root) {
if (root == null) return;
TreeNode t = root.left;
root.left = root.right;
root.right = t;
Mirror(root.left);
Mirror(root.right);
}
28.1 對稱的二叉樹
boolean isSymmetrical(TreeNode pRoot) {
if (pRoot == null) return true;
return isSymmetrical(pRoot.left, pRoot.right);
}
boolean isSymmetrical(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
if (t1.val != t2.val) return false;
return isSymmetrical(t1.left, t2.right) && isSymmetrical(t1.right, t2.left);
}
28.2 平衡二叉樹
private boolean isBalanced = true;
public boolean IsBalanced_Solution(TreeNode root) {
height(root);
return isBalanced;
}
private int height(TreeNode root) {
if (root == null) return 0;
int left = height(root.left);
int right = height(root.right);
if (Math.abs(left - right) > 1) isBalanced = false;
return 1 + Math.max(left, right);
}
29. 順時針打印矩陣
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> ret = new ArrayList<>();
int r1 = 0, r2 = matrix.length - 1, c1 = 0, c2 = matrix[0].length - 1;
while (r1 <= r2 && c1 <= c2) {
for (int i = c1; i <= c2; i++) ret.add(matrix[r1][i]);
for (int i = r1 + 1; i <= r2; i++) ret.add(matrix[i][c2]);
if (r1 != r2) for (int i = c2 - 1; i >= c1; i--) ret.add(matrix[r2][i]);
if (c1 != c2) for (int i = r2 - 1; i > r1; i--) ret.add(matrix[i][c1]);
r1++; r2--; c1++; c2--;
}
return ret;
}
30. 包含 min 函數的棧
private Stack<Integer> stack = new Stack<>();
private Stack<Integer> minStack = new Stack<>();
private int min = Integer.MAX_VALUE;
public void push(int node) {
stack.push(node);
if (min > node) min = node;
minStack.push(min);
}
public void pop() {
stack.pop();
minStack.pop();
min = minStack.peek();
}
public int top() {
return stack.peek();
}
public int min() {
return minStack.peek();
}
31. 棧的壓入、彈出序列
public boolean IsPopOrder(int[] pushA, int[] popA) {
int n = pushA.length;
Stack<Integer> stack = new Stack<>();
for (int i = 0, j = 0; i < n; i++) {
stack.push(pushA[i]);
while (j < n && stack.peek() == popA[j]) {
stack.pop();
j++;
}
}
return stack.isEmpty();
}
32.1 從上往下打印二叉樹
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
ArrayList<Integer> ret = new ArrayList<>();
if (root == null) return ret;
queue.add(root);
while (!queue.isEmpty()) {
int cnt = queue.size();
for (int i = 0; i < cnt; i++) {
TreeNode t = queue.poll();
if (t.left != null) queue.add(t.left);
if (t.right != null) queue.add(t.right);
ret.add(t.val);
}
}
return ret;
}
32.3 把二叉樹打印成多行
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
if (pRoot == null) return ret;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
while (!queue.isEmpty()) {
int cnt = queue.size();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < cnt; i++) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
ret.add(list);
}
return ret;
}
32.3 按之字形順序打印二叉樹
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
if (pRoot == null) return ret;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
boolean reverse = false;
while (!queue.isEmpty()) {
int cnt = queue.size();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < cnt; i++) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
if (reverse) {
Collections.reverse(list);
reverse = false;
} else {
reverse = true;
}
ret.add(list);
}
return ret;
}
33. 二叉搜索樹的後序遍歷序列
public boolean VerifySquenceOfBST(int[] sequence) {
if (sequence.length == 0) return false;
return verify(sequence, 0, sequence.length - 1);
}
private boolean verify(int[] sequence, int start, int end) {
if (end - start <= 1) return true;
int rootVal = sequence[end];
int cutIdx = start;
while (cutIdx < end) {
if (sequence[cutIdx] > rootVal) break;
cutIdx++;
}
for (int i = cutIdx + 1; i < end; i++) {
if (sequence[i] < rootVal) return false;
}
return verify(sequence, start, cutIdx - 1) && verify(sequence, cutIdx, end - 1);
}
34. 二叉樹中和爲某一值的路徑
private ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
dfs(root, target, 0, new ArrayList<>());
return ret;
}
private void dfs(TreeNode node, int target, int curSum, ArrayList<Integer> path) {
if (node == null) return;
curSum += node.val;
path.add(node.val);
if (curSum == target && node.left == null && node.right == null) {
ret.add(new ArrayList(path));
} else {
dfs(node.left, target, curSum, path);
dfs(node.right, target, curSum, path);
}
path.remove(path.size() - 1);
}
35. 複雜鏈表的複製
題目描述
輸入一個複雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的 head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)
第一步,在每個節點的後面插入複製的節點。
第二步,對複製節點的 random 鏈接進行賦值。
第三步,拆分。
public RandomListNode Clone(RandomListNode pHead) {
if (pHead == null) return null;
// 插入新節點
RandomListNode cur = pHead;
while (cur != null) {
RandomListNode node = new RandomListNode(cur.label);
node.next = cur.next;
cur.next = node;
cur = node.next;
}
// 建立 random 鏈接
cur = pHead;
while (cur != null) {
RandomListNode clone = cur.next;
if (cur.random != null) {
clone.random = cur.random.next;
}
cur = clone.next;
}
// 拆分
RandomListNode pCloneHead = pHead.next;
cur = pHead;
while (cur.next != null) {
RandomListNode t = cur.next;
cur.next = t.next;
cur = t;
}
return pCloneHead;
}
36. 二叉搜索樹與雙向鏈表
題目描述
輸入一棵二叉搜索樹,將該二叉搜索樹轉換成一個排序的雙向鏈表。要求不能創建任何新的結點,只能調整樹中結點指針的指向。
private TreeNode pre = null;
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null) return null;
inOrder(pRootOfTree);
while(pRootOfTree.left != null) pRootOfTree = pRootOfTree.left;
return pRootOfTree;
}
private void inOrder(TreeNode node) {
if(node == null) return;
inOrder(node.left);
node.left = pre;
if(pre != null) pre.right = node;
pre = node;
inOrder(node.right);
}
37. 序列化二叉樹
private String serizeString = "";
String Serialize(TreeNode root) {
if (root == null) return "#";
return root.val + " " + Serialize(root.left) + " "
+ Serialize(root.right);
}
TreeNode Deserialize(String str) {
this.serizeString = str;
return Deserialize();
}
private TreeNode Deserialize() {
if (this.serizeString.length() == 0) return null;
int idx = this.serizeString.indexOf(" ");
if (idx == -1) return null;
String sub = this.serizeString.substring(0, idx);
this.serizeString = this.serizeString.substring(idx + 1);
if (sub.equals("#")) {
return null;
}
int val = Integer.valueOf(sub);
TreeNode t = new TreeNode(val);
t.left = Deserialize();
t.right = Deserialize();
return t;
}
38. 字符串的排列
題目描述
輸入一個字符串 , 按字典序打印出該字符串中字符的所有排列。例如輸入字符串 abc, 則打印出由字符 a, b, c 所能排列出來的所有字符串 abc, acb, bac, bca, cab 和 cba。
private ArrayList<String> ret = new ArrayList<>();
public ArrayList<String> Permutation(String str) {
if (str.length() == 0) return new ArrayList<>();
char[] chars = str.toCharArray();
Arrays.sort(chars);
backtracking(chars, new boolean[chars.length], "");
return ret;
}
private void backtracking(char[] chars, boolean[] used, String s) {
if (s.length() == chars.length) {
ret.add(s);
return;
}
for (int i = 0; i < chars.length; i++) {
if (used[i]) continue;
if (i != 0 && chars[i] == chars[i - 1] && !used[i - 1]) continue; // 保證不重複
used[i] = true;
backtracking(chars, used, s + chars[i]);
used[i] = false;
}
}
第五章 優化時間和空間效率
39. 數組中出現次數超過一半的數字
public int MoreThanHalfNum_Solution(int[] array) {
int cnt = 1, num = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] == num) cnt++;
else cnt--;
if (cnt == 0) {
num = array[i];
cnt = 1;
}
}
cnt = 0;
for (int i = 0; i < array.length; i++) {
if (num == array[i]) cnt++;
}
return cnt > array.length / 2 ? num : 0;
}
40. 最小的 K 個數
構建大小爲 k 的小頂堆。
時間複雜度:O(nlgk)空間複雜度:O(k)
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
if (k > input.length || k <= 0) return new ArrayList<>();
PriorityQueue<Integer> pq = new PriorityQueue<>((o1, o2) -> o2 - o1);
for (int num : input) {
pq.add(num);
if (pq.size() > k) {
pq.poll();
}
}
ArrayList<Integer> ret = new ArrayList<>(pq);
return ret;
}
利用快速選擇
時間複雜度:O(n)空間複雜度:O(1)
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
if (k > input.length || k <= 0) return new ArrayList<>();
int kthSmallest = findKthSmallest(input, k - 1);
ArrayList<Integer> ret = new ArrayList<>();
for (int num : input) {
if(num <= kthSmallest && ret.size() < k) ret.add(num);
}
return ret;
}
public int findKthSmallest(int[] nums, int k) {
int lo = 0;
int hi = nums.length - 1;
while (lo < hi) {
int j = partition(nums, lo, hi);
if (j < k) {
lo = j + 1;
} else if (j > k) {
hi = j - 1;
} else {
break;
}
}
return nums[k];
}
private int partition(int[] a, int lo, int hi) {
int i = lo;
int j = hi + 1;
while (true) {
while (i < hi && less(a[++i], a[lo])) ;
while (j > lo && less(a[lo], a[--j])) ;
if (i >= j) {
break;
}
exch(a, i, j);
}
exch(a, lo, j);
return j;
}
private void exch(int[] a, int i, int j) {
final int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
private boolean less(int v, int w) {
return v < w;
}
41.1 數據流中的中位數
題目描述
如何得到一個數據流中的中位數?如果從數據流中讀出奇數個數值,那麼中位數就是所有數值排序之後位於中間的數值。如果從數據流中讀出偶數個數值,那麼中位數就是所有數值排序之後中間兩個數的平均值。
private PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1, o2) -> o2-o1); // 實現左邊部分
private PriorityQueue<Integer> minHeep = new PriorityQueue<>(); // 實現右邊部分,右邊部分所有元素大於左邊部分
private int cnt = 0;
public void Insert(Integer num) {
// 插入要保證兩個堆存於平衡狀態
if(cnt % 2 == 0) {
// 爲偶數的情況下插入到最小堆,先經過最大堆篩選,這樣就能保證最大堆中的元素都小於最小堆中的元素
maxHeap.add(num);
minHeep.add(maxHeap.poll());
} else {
minHeep.add(num);
maxHeap.add(minHeep.poll());
}
cnt++;
}
public Double GetMedian() {
if(cnt % 2 == 0) {
return (maxHeap.peek() + minHeep.peek()) / 2.0;
} else {
return (double) minHeep.peek();
}
}
14.2 字符流中第一個不重複的字符
題目描述
請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符 "go" 時,第一個只出現一次的字符是 "g"。當從該字符流中讀出前六個字符“google" 時,第一個只出現一次的字符是 "l"。
//Insert one char from stringstream
private int[] cnts = new int[256];
private Queue<Character> queue = new LinkedList<>();
public void Insert(char ch) {
cnts[ch]++;
queue.add(ch);
while (!queue.isEmpty() && cnts[queue.peek()] > 1) {
queue.poll();
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce() {
if (queue.isEmpty()) return '#';
return queue.peek();
}
42. 連續子數組的最大和
public int FindGreatestSumOfSubArray(int[] array) {
if(array.length == 0) return 0;
int ret = Integer.MIN_VALUE;
int sum = 0;
for(int num : array) {
if(sum <= 0) sum = num;
else sum += num;
ret = Math.max(ret, sum);
}
return ret;
}
43. 從 1 到 n 整數中 1 出現的次數
解題參考:Leetcode : 233. Number of Digit One
public int NumberOf1Between1AndN_Solution(int n) {
int cnt = 0;
for (int m = 1; m <= n; m *= 10) {
int a = n / m, b = n % m;
cnt += (a + 8) / 10 * m + (a % 10 == 1 ? b + 1 : 0);
}
return cnt;
}
45. 把數組排成最小的數
題目描述
輸入一個正整數數組,把數組裏所有數字拼接起來排成一個數,打印能拼接出的所有數字中最小的一個。例如輸入數組 {3,32,321},則打印出這三個數字能排成的最小數字爲 321323。
public String PrintMinNumber(int[] numbers) {
int n = numbers.length;
String[] nums = new String[n];
for (int i = 0; i < n; i++) nums[i] = numbers[i] + "";
Arrays.sort(nums, (s1, s2) -> (s1 + s2).compareTo(s2 + s1));
String ret = "";
for (String str : nums) ret += str;
return ret;
}
49. 醜數
題目描述
把只包含因子 2、3 和 5 的數稱作醜數(Ugly Number)。例如 6、8 都是醜數,但 14 不是,因爲它包含因子 7。 習慣上我們把 1 當做是第一個醜數。求按從小到大的順序的第 N 個醜數。
public int GetUglyNumber_Solution(int index) {
if (index <= 6) return index;
int i2 = 0, i3 = 0, i5 = 0;
int cnt = 1;
int[] dp = new int[index];
dp[0] = 1;
while (cnt < index) {
int n2 = dp[i2] * 2, n3 = dp[i3] * 3, n5 = dp[i5] * 5;
int tmp = Math.min(n2, Math.min(n3, n5));
dp[cnt++] = tmp;
if (tmp == n2) i2++;
if (tmp == n3) i3++;
if (tmp == n5) i5++;
}
return dp[index - 1];
}
50. 第一個只出現一次的字符位置
public int FirstNotRepeatingChar(String str) {
int[] cnts = new int[256];
for (int i = 0; i < str.length(); i++) cnts[str.charAt(i)]++;
for (int i = 0; i < str.length(); i++) if (cnts[str.charAt(i)] == 1) return i;
return -1;
}
51. 數組中的逆序對
private long cnt = 0;
public int InversePairs(int[] array) {
mergeSortUp2Down(array, 0, array.length - 1);
return (int) (cnt % 1000000007);
}
private void mergeSortUp2Down(int[] a, int start, int end) {
if (end - start < 1) return;
int mid = start + (end - start) / 2;
mergeSortUp2Down(a, start, mid);
mergeSortUp2Down(a, mid + 1, end);
merge(a, start, mid, end);
}
private void merge(int[] a, int start, int mid, int end) {
int[] tmp = new int[end - start + 1];
int i = start, j = mid + 1, k = 0;
while (i <= mid || j <= end) {
if (i > mid) tmp[k] = a[j++];
else if (j > end) tmp[k] = a[i++];
else if (a[i] < a[j]) tmp[k] = a[i++];
else {
tmp[k] = a[j++];
this.cnt += mid - i + 1; // a[i] > a[j] ,說明 a[i...mid] 都大於 a[j]
}
k++;
}
for (k = 0; k < tmp.length; k++) {
a[start + k] = tmp[k];
}
}
52. 兩個鏈表的第一個公共結點
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode l1 = pHead1, l2 = pHead2;
while (l1 != l2) {
if (l1 == null) l1 = pHead2;
else l1 = l1.next;
if (l2 == null) l2 = pHead1;
else l2 = l2.next;
}
return l1;
}
第六章 面試中的各項能力
53 數字在排序數組中出現的次數
public int GetNumberOfK(int[] array, int k) {
int l = 0, h = array.length - 1;
while (l <= h) {
int m = l + (h - l) / 2;
if (array[m] >= k) h = m - 1;
else l = m + 1;
}
int cnt = 0;
while (l < array.length && array[l++] == k) cnt++;
return cnt;
}
54. 二叉搜索樹的第 k 個結點
TreeNode ret;
int cnt = 0;
TreeNode KthNode(TreeNode pRoot, int k) {
inorder(pRoot, k);
return ret;
}
private void inorder(TreeNode root, int k) {
if (root == null) return;
if (cnt > k) return;
inorder(root.left, k);
cnt++;
if (cnt == k) ret = root;
inorder(root.right, k);
}
55 二叉樹的深度
public int TreeDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(TreeDepth(root.left), TreeDepth(root.right));
}
56. 數組中只出現一次的數字
題目描述
一個整型數組裏除了兩個數字之外,其他的數字都出現了兩次,找出這兩個數。
解題思路
兩個不相等的元素在位級表示上必定會有一位存在不同。
將數組的所有元素異或得到的結果爲不存在重複的兩個元素異或的結果。
diff &= -diff 得到出 diff 最右側不爲 0 的位,也就是不存在重複的兩個元素在位級表示上最右側不同的那一位,利用這一位就可以將兩個元素區分開來。
public void FindNumsAppearOnce(int[] array, int num1[], int num2[]) {
int diff = 0;
for (int num : array) diff ^= num;
// 得到最右一位
diff &= -diff;
for (int num : array) {
if ((num & diff) == 0) num1[0] ^= num;
else num2[0] ^= num;
}
}
57.1 和爲 S 的兩個數字
題目描述
輸入一個遞增排序的數組和一個數字 S,在數組中查找兩個數,是的他們的和正好是 S,如果有多對數字的和等於 S,輸出兩個數的乘積最小的。
public ArrayList<Integer> FindNumbersWithSum(int[] array, int sum) {
int i = 0, j = array.length - 1;
while (i < j) {
int cur = array[i] + array[j];
if (cur == sum) return new ArrayList<Integer>(Arrays.asList(array[i], array[j]));
else if (cur < sum) i++;
else j--;
}
return new ArrayList<Integer>();
}
57.2 和爲 S 的連續正數序列
題目描述
和爲 100 的連續序列有 18, 19, 20, 21, 22
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
int start = 1, end = 2;
int mid = sum / 2;
int curSum = 3;
while (start <= mid && end < sum) {
if (curSum > sum) {
curSum -= start;
start++;
} else if (curSum < sum) {
end++;
curSum += end;
} else {
ArrayList<Integer> list = new ArrayList<>();
for (int i = start; i <= end; i++) {
list.add(i);
}
ret.add(list);
curSum -= start;
start++;
end++;
curSum += end;
}
}
return ret;
}
58.1 翻轉單詞順序列
題目描述
輸入:"I am a student."
輸出:"student. a am I"
public String ReverseSentence(String str) {
if (str.length() == 0) return str;
int n = str.length();
char[] chars = str.toCharArray();
int start = 0, end = 0;
while (end <= n) {
if (end == n || chars[end] == ' ') {
reverse(chars, start, end - 1);
start = end + 1;
}
end++;
}
reverse(chars, 0, n - 1);
return new String(chars);
}
private void reverse(char[] c, int start, int end) {
while (start < end) {
char t = c[start];
c[start] = c[end];
c[end] = t;
start++;
end--;
}
}
58.2 左旋轉字符串
題目描述
對於一個給定的字符序列 S,請你把其循環左移 K 位後的序列輸出。例如,字符序列 S=”abcXYZdef”, 要求輸出循環左移 3 位後的結果,即“XYZdefabc”。
public String LeftRotateString(String str, int n) {
if (str.length() == 0) return "";
char[] c = str.toCharArray();
reverse(c, 0, n - 1);
reverse(c, n, c.length - 1);
reverse(c, 0, c.length - 1);
return new String(c);
}
private void reverse(char[] c, int i, int j) {
while (i < j) {
char t = c[i];
c[i] = c[j];
c[j] = t;
i++;
j--;
}
}
59. 滑動窗口的最大值
題目描述
給定一個數組和滑動窗口的大小,找出所有滑動窗口裏數值的最大值。例如,如果輸入數組 {2, 3, 4, 2, 6, 2, 5, 1} 及滑動窗口的大小 3,那麼一共存在 6 個滑動窗口,他們的最大值分別爲 {4, 4, 6, 6, 6, 5};
public ArrayList<Integer> maxInWindows(int[] num, int size) {
ArrayList<Integer> ret = new ArrayList<>();
if (size > num.length || size < 1) return ret;
PriorityQueue<Integer> heap = new PriorityQueue<Integer>((o1, o2) -> o2 - o1);
for (int i = 0; i < size; i++) heap.add(num[i]);
ret.add(heap.peek());
for (int i = 1; i + size - 1 < num.length; i++) {
heap.remove(num[i - 1]);
heap.add(num[i + size - 1]);
ret.add(heap.peek());
}
return ret;
}
61. 撲克牌順子
題目描述
五張牌,其中大小鬼爲癩子,牌面大小爲 0。判斷是否能組成順子。
public boolean isContinuous(int[] numbers) {
if (numbers.length < 5) return false;
Arrays.sort(numbers);
int cnt = 0;
for (int num : numbers) if (num == 0) cnt++;
for (int i = cnt; i < numbers.length - 1; i++) {
if (numbers[i + 1] == numbers[i]) return false;
int cut = numbers[i + 1] - numbers[i] - 1;
if (cut > cnt) return false;
cnt -= cut;
}
return true;
}
62. 圓圈中最後剩下的數
題目描述
讓小朋友們圍成一個大圈。然後 , 他隨機指定一個數 m, 讓編號爲 0 的小朋友開始報數。每次喊到 m-1 的那個小朋友要出列唱首歌 , 然後可以在禮品箱中任意的挑選禮物 , 並且不再回到圈中 , 從他的下一個小朋友開始 , 繼續 0...m-1 報數 .... 這樣下去 .... 直到剩下最後一個小朋友 , 可以不用表演。
解題思路
約瑟夫環
public int LastRemaining_Solution(int n, int m) {
if (n == 0) return -1;
if (n == 1) return 0;
return (LastRemaining_Solution(n - 1, m) + m) % n;
}
63. 股票的最大利潤
題目描述
可以有一次買入和一次賣出,買入必須在前。求最大收益。
public int maxProfit(int[] prices) {
int n = prices.length;
if(n == 0) return 0;
int soFarMin = prices[0];
int max = 0;
for(int i = 1; i < n; i++) {
if(soFarMin > prices[i]) soFarMin = prices[i];
else max = Math.max(max, prices[i] - soFarMin);
}
return max;
}
64. 求 1+2+3+...+n
題目描述
求 1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case 等關鍵字及條件判斷語句(A?B:C)
public int Sum_Solution(int n) {
if(n == 0) return 0;
return n + Sum_Solution(n - 1);
}
65. 不用加減乘除做加法
a ^ b 表示沒有考慮進位的情況下兩數的和,(a & b) << 1 就是進位。遞歸會終止的原因是 (a & b) << 1 最右邊會多一個 0,那麼繼續遞歸,進位最右邊的 0 會慢慢增多,最後進位會變爲 0,遞歸終止。
public int Add(int num1, int num2) {
if(num2 == 0) return num1;
return Add(num1 ^ num2, (num1 & num2) << 1);
}
66. 構建乘積數組
題目描述
給定一個數組 A[0, 1,..., n-1], 請構建一個數組 B[0, 1,..., n-1], 其中 B 中的元素 B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。
public int[] multiply(int[] A) {
int n = A.length;
int[][] dp = new int[n][n];
for (int i = 0; i < n; i++) {
dp[i][i] = A[i];
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
dp[i][j] = dp[i][j - 1] * A[j];
}
}
int[] B = new int[n];
Arrays.fill(B, 1);
for (int i = 0; i < n; i++) {
if (i != 0) B[i] *= dp[0][i - 1];
if (i != n - 1) B[i] *= dp[i + 1][n - 1];
}
return B;
}
第七章 兩個面試案例
67. 把字符串轉換成整數
public int StrToInt(String str) {
if (str.length() == 0) return 0;
char[] chars = str.toCharArray();
boolean isNegative = chars[0] == '-';
int ret = 0;
for (int i = 0; i < chars.length; i++) {
if (i == 0 && (chars[i] == '+' || chars[i] == '-')) continue;
if (chars[i] < '0' || chars[i] > '9') return 0;
ret = ret * 10 + (chars[i] - '0');
}
return isNegative ? -ret : ret;
}
68. 樹中兩個節點的最低公共祖先
樹是二叉查找樹的最低公共祖先問題:
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
if(root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
return root;
}