剑指offer ------ 刷题总结

面试题3 -- 搜索二维矩阵

写出一个高效的算法来搜索 m × n矩阵中的值。

这个矩阵具有以下特性:

1. 每行中的整数从左到右是排序的。

2. 每行的第一个数大于上一行的最后一个整数。

思路:二分位置0 ~ n * m - 1

 1 public class Solution {
 2     /**
 3      * @param matrix, a list of lists of integers
 4      * @param target, an integer
 5      * @return a boolean, indicate whether matrix contains target
 6      */
 7     public boolean searchMatrix(int[][] matrix, int target) {
 8         // write your code here
 9         if (matrix == null || matrix.length == 0) {
10             return false;
11         }
12         int rows = matrix.length;
13         int columns = matrix[0].length;
14         int start = 0;
15         int end = rows * columns - 1;
16         while (start + 1 < end) {
17             int mid = start + (end - start) / 2;
18             if (matrix[mid / columns][mid % columns] == target) {
19                 return true;
20             } else if (matrix[mid / columns][mid % columns] < target) {
21                 start = mid;
22             } else {
23                 end = mid;
24             }
25         }
26         if (matrix[start / columns][start % columns] == target) {
27             return true;
28         } else if (matrix[end / columns][end % columns] == target) {
29             return true;
30         }
31         return false;
32     }
33 }
View Code

拓展 -- 搜索二维矩阵 II

写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。

这个矩阵具有以下特性:

1. 每行中的整数从左到右是排序的。

2. 每一列的整数从上到下是排序的。

3. 在每一行或每一列中没有重复的整数。

思路:从二维矩阵的右上角(左下角)开始搜索,每次当该位置的值等于target,等于target的个数+1,删除该位置所在的行和列,移动行指针和列指针;小于target,删除该位置所在的行,移动行指针;大于target,删除该位置所在的列,移动列指针。

 1 public class Solution {
 2     /**
 3      * @param matrix: A list of lists of integers
 4      * @param: A number you want to search in the matrix
 5      * @return: An integer indicate the occurrence of target in the given matrix
 6      */
 7     public int searchMatrix(int[][] matrix, int target) {
 8         // write your code here
 9         if (matrix == null || matrix.length == 0) {
10             return 0;
11         }
12         int rows = matrix.length;
13         int columns = matrix[0].length;
14         int row = 0;
15         int column = columns - 1;
16         int count = 0;
17         while (row <= rows - 1 && column >= 0) {
18             if (matrix[row][column] == target) {
19                 count++;
20                 row++;
21                 column--;
22             } else if (matrix[row][column] > target) {
23                 column--;
24             } else {
25                 row++;
26             }
27         }
28         return count;
29     }
30 }
View Code

  

求Fibonacci第n个数(从1开始)

初级:递归(当n很大时时间复杂度很高,会有重复递归问题)。

 1 class Solution {
 2     /**
 3      * @param n: an integer
 4      * @return an integer f(n)
 5      */
 6     public int fibonacci(int n) {
 7         // write your code here
 8         if (n == 1) {
 9             return 0;
10         }
11         if (n == 2) {
12             return 1;
13         }
14         return fibonacci(n - 1) + fibonacci(n  - 2);
15     }
16 }
View Code

中级:使用map存储递归过程中得到的F[i],键值对-[i, F(i)],可以避免重复递归问题。

 1 class Solution {
 2     /**
 3      * @param n: an integer
 4      * @return an integer f(n)
 5      */
 6     public int fibonacci(int n) {
 7         // write your code here
 8         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
 9         return fibonacci(n, map);
10     }
11     public int fibonacci(int n, Map<Integer, Integer> map) {
12         if (n == 1) {
13             map.put(1, 0);
14             return 0;
15         }
16         if (n == 2) {
17             map.put(2, 1);
18             return 1;
19         }
20         int sum = 0;
21         if (map.containsKey(n - 1)) {
22             sum += map.get(n - 1);
23         } else {
24             int temp = fibonacci(n - 1, map);
25             map.put(n - 1, temp);
26             sum += temp;
27         }
28         if (map.containsKey(n - 2)) {
29             sum += map.get(n - 2);
30         } else {
31             int temp = fibonacci(n - 2, map);
32             map.put(n - 2, temp);
33             sum += temp;
34         }
35         return sum;
36     }
37 }
View Code

高级:直接根据F(1)和F(2)求的F(3),再由F(2)和F(3)求的F(4)......以此类推知道求得F(n)停止。

 1 class Solution {
 2     /**
 3       * @param n: an integer
 4       * @return an integer f(n)
 5       */
 6      public int fibonacci(int n) {
 7          // write your code here
 8          if (n == 1) {
 9              return 0;
10          }
11          if (n == 2) {
12              return 1;
13          }
14          int fibNMinusTwo = 0;
15          int fibNMinusOne = 1;
16          int fibN = 0;
17          for (int i = 3; i <= n; i++) {
18              fibN = fibNMinusTwo + fibNMinusOne;
19              fibNMinusTwo = fibNMinusOne;
20              fibNMinusOne = fibN;
21          }
22          return fibN;
23      }
24  }
View Code

 

拓展 -- 爬楼梯

假设你正在爬楼梯,需要n步你才能到达顶部。但每次你只能爬一步或者两步,你能有多少种不同的方法爬到楼顶部?

思路I:类似斐波那契数列的求解过程

 1 public class Solution {
 2     /**
 3      * @param n: An integer
 4      * @return: An integer
 5      */
 6     public int climbStairs(int n) {
 7         // write your code here
 8         if (n <= 1) {
 9             return 1;
10         }
11         int stairsNMinusTwo = 1;
12         int stairsNMinusOne = 1;
13         int stairsN = 0;
14         for (int i = 2; i <= n; i++) {
15             stairsN = stairsNMinusTwo + stairsNMinusOne;
16             stairsNMinusTwo = stairsNMinusOne;
17             stairsNMinusOne = stairsN;
18         }
19         return stairsN;
20     }
21 }
View Code

 思路II:dp + 滚动数组优化

 1 public class Solution {
 2     /**
 3      * @param n: An integer
 4      * @return: An integer
 5      */
 6     public int climbStairs(int n) {
 7         // write your code here
 8         if (n == 0) {
 9             return 0;
10         }
11         if (n == 1) {
12             return 1;
13         }
14         int[] dp = new int[2];
15         dp[0] = 1;
16         dp[1] = 1;
17         for (int i = 2; i <= n; i++) {
18             dp[i % 2] = dp[(i - 1) % 2] + dp[(i - 2) % 2];
19         }
20         return dp[n % 2];
21     }
22 }
View Code

 

 

拓展 -- 爬楼梯II

一个小孩爬一个 n 层台阶的楼梯。他可以每次跳 1 步, 2 步 或者 3 步。实现一个方法来统计总共有多少种不同的方式爬到最顶层的台阶。

 1 public class Solution {
 2     /**
 3      * @param n an integer
 4      * @return an integer
 5      */
 6     public int climbStairs2(int n) {
 7         // Write your code here
 8         if (n <= 1) {
 9             return 1;
10         }
11         if (n == 2) {
12             return 2;
13         }
14         int stairsNMinusThree = 1;
15         int stairsNMinusTwo = 1;
16         int stairsNMinusOne = 2;
17         int stairsN = 0;
18         for (int i = 3; i <= n; i++) {
19             stairsN = stairsNMinusThree + stairsNMinusTwo + stairsNMinusOne;
20             stairsNMinusThree = stairsNMinusTwo;
21             stairsNMinusTwo = stairsNMinusOne;
22             stairsNMinusOne = stairsN;
23         }
24         return stairsN;
25     }
26 }
View Code

 

空格替换

设计一种方法,将一个字符串中的所有空格替换成 %20。你可以假设该字符串有足够的空间来加入新的字符,且你得到的是“真实的”字符长度。

你的程序还需要返回被替换后的字符串的长度。如果使用 Java 或 Python, 程序中请用字符数组表示字符串。

 1 public class Solution {
 2     /**
 3      * @param string: An array of Char
 4      * @param length: The true length of the string
 5      * @return: The true length of new string
 6      */
 7     public int replaceBlank(char[] string, int length) {
 8         // Write your code here
 9         if (string == null || string.length == 0) {
10             return 0;
11         }
12         int prePointer = 0;
13         int afterPointer = 0;
14         int blankNumber = 0;
15         for (int i = 0; string[i] != '\0'; i++) {
16             if (string[i] == ' ') {
17                 blankNumber++;
18             }
19             prePointer++;
20         }
21         afterPointer = prePointer + 2 * blankNumber;
22         int result = afterPointer;
23         while (prePointer >= 0 && prePointer != afterPointer) {
24             if (string[prePointer] != ' ') {
25                 string[afterPointer] = string[prePointer];
26                 afterPointer--;
27             } else {
28                 string[afterPointer--] = '0';
29                 string[afterPointer--] = '2';
30                 string[afterPointer--] = '%';
31             }
32             prePointer--;
33         }
34         return result;
35     }
36 }
View Code

 

面试题10 -- 二进制中1的个数

计算在一个 32 位的整数的二进制表式中有多少个 1

常规:1不断左移一位并与给定的数⬅️与运算,如果为0说明该位为1,count++,左移次数从0 - 31.

 1 public class Solution {
 2     /**
 3      * @param num: an integer
 4      * @return: an integer, the number of ones in num
 5      */
 6     public int countOnes(int num) {
 7         // write your code here
 8         int count = 0;
 9         int flag = 1;
10         for (int i = 0; i < 32; i++) {
11             if ((num & flag) != 0) {
12                 count++;
13             }
14             flag = flag << 1;
15         }
16         return count;
17     }
18 }
View Code

高级:把一个整数减去1,再和原整数作与运算,会把该整数最右边一个1变成0

 1 public class Solution {
 2     /**
 3      * @param num: an integer
 4      * @return: an integer, the number of ones in num
 5      */
 6     public int countOnes(int num) {
 7         // write your code here
 8         int count = 0;
 9         while (num != 0) {
10             num = (num - 1) & num;
11             count++;
12         }
13         return count;
14     }
15 }
View Code

 

 面试题16 -- 翻转链表

一刷的时候没有注意到先建一个临时节点来保存当前节点cur的下一个节点,导致cur移到下一个节点的时候出现错误!!!不保存下一个节点的话链表会断开!!!

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param head: The head of linked list.
15      * @return: The new head of reversed linked list.
16      */
17     public ListNode reverse(ListNode head) {
18         // write your code here
19         if (head == null || head.next == null) {
20             return head;
21         }
22         ListNode prev = head;
23         ListNode cur = head.next;
24         while (cur != null) {
25             //这句代码必不可少!操作前必须先保存下一个节点!
26             ListNode after = cur.next;
27             cur.next = prev;
28             prev = cur;
29             cur = after;
30         }
31         head.next = null;
32         return prev;
33     }
34 }
View Code

拓展 -- 翻转链表II

翻转链表中第m个节点到第n个节点的部分。m,n满足1 ≤ m ≤ n ≤ 链表长度。

 1 /**
 2  * Definition for ListNode
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param ListNode head is the head of the linked list
15      * @oaram m and n
16      * @return: The head of the reversed ListNode
17      */
18     public ListNode reverseBetween(ListNode head, int m , int n) {
19         // write your code
20         if (head == null || head.next == null) {
21             return head;
22         }
23         ListNode fakeHead = new ListNode(0);
24         fakeHead.next = head;
25         ListNode pre = fakeHead;
26         for (int i = 0; i < m - 1; i++) {
27             pre = pre.next;
28         }
29         ListNode cur = pre.next;
30         ListNode after = cur.next;
31         for (int i = 0; i < n - m; i++) {
32             cur.next = after.next;
33             after.next = pre.next;
34             pre.next = after;
35             after = cur.next;
36         }
37         return fakeHead.next;
38     }
39 }
View Code

 

版本II

 1 /**
 2  * Definition for ListNode
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param head: ListNode head is the head of the linked list 
17      * @param m: An integer
18      * @param n: An integer
19      * @return: The head of the reversed ListNode
20      */
21     public ListNode reverseBetween(ListNode head, int m, int n) {
22         // write your code here
23         if (head == null || head.next == null) {
24             return head;
25         }
26         ListNode dummy = new ListNode(0);
27         dummy.next = head;
28         ListNode nodeMMinus = dummy;
29         for (int i = 0; i < m - 1; i++) {
30             nodeMMinus = nodeMMinus.next;
31         }
32         ListNode nodeM = nodeMMinus.next;
33         ListNode pre = null, cur = nodeM;
34         for (int i = 0; i < n - m + 1; i++) {
35             ListNode next = cur.next;
36             cur.next = pre;
37             pre = cur;
38             cur = next;
39         }
40         ListNode nodeN = pre;
41         nodeMMinus.next = nodeN;
42         nodeM.next = cur;
43         return dummy.next;
44     }
45 }
View Code

 

面试题6 -- 前序遍历和中序遍历树构造二叉树

你可以假设树中不存在相同数值的节点

注意构造二叉树的过程分析。

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      *@param preorder : A list of integers that preorder traversal of a tree
15      *@param inorder : A list of integers that inorder traversal of a tree
16      *@return : Root of a tree
17      */
18     public TreeNode buildTree(int[] preorder, int[] inorder) {
19         // write your code here
20         return helper(preorder, inorder, 0, 0, inorder.length - 1);
21     }
22     public TreeNode helper(int[] preorder, int[] inorder, int preStart,
23         int inStart, int inEnd) {
24         if (inStart > inEnd) {
25             return null;
26         }
27         TreeNode root = new TreeNode(preorder[preStart]);
28         int inRootIndex = 0;
29         for (int i = 0; i < inorder.length; i++) {
30             if (preorder[preStart] == inorder[i]) {
31                 inRootIndex = i;
32             }
33         }
34         root.left = helper(preorder, inorder, preStart + 1, inStart, inRootIndex - 1);
35         root.right = helper(preorder, inorder,
36             preStart + inRootIndex - inStart + 1, inRootIndex + 1, inEnd);
37         return root;
38     }
39 }
View Code

 

拓展 -- 中序遍历和后序遍历树构造二叉树

 根据中序遍历和后序遍历树构造二叉树,你可以假设树中不存在相同数值的节点。

思路同上。

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      *@param inorder : A list of integers that inorder traversal of a tree
15      *@param postorder : A list of integers that postorder traversal of a tree
16      *@return : Root of a tree
17      */
18     public TreeNode buildTree(int[] inorder, int[] postorder) {
19         // write your code here
20        return buildTreeHelper(inorder, postorder, postorder.length - 1,
21             0, inorder.length - 1);
22     }
23     public TreeNode buildTreeHelper(int[] inorder, int[] postorder,
24         int postStart, int inStart, int inEnd) {
25         if (inStart > inEnd) {
26             return null;
27         }
28         TreeNode root = new TreeNode(postorder[postStart]);
29         int inRootIndex = 0;
30         for (int i = 0; i < inorder.length; i++) {
31             if (postorder[postStart] == inorder[i]) {
32                 inRootIndex = i;
33             }
34         }
35         root.left = buildTreeHelper(inorder, postorder,
36             postStart - (inEnd - inRootIndex) - 1, inStart, inRootIndex - 1);
37         root.right = buildTreeHelper(inorder, postorder, postStart - 1,
38             inRootIndex + 1, inEnd);
39         return root;
40     }
41 }
View Code

 

面试题7 -- 用栈实现队列

正如标题所述,你需要使用两个栈来实现队列的一些操作。

队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。

pop和top方法都应该返回第一个元素的值。

核心思路:stack1只管用来将元素压栈,stack2只管将元素弹出栈,如果为空就从stack1里将元素全部压入stack2再弹出,注意判空操作。

 1 public class Queue {
 2     private Stack<Integer> stack1;
 3     private Stack<Integer> stack2;
 4 
 5     public Queue() {
 6        // do initialization if necessary
 7        stack1 = new Stack<Integer>();
 8        stack2 = new Stack<Integer>();
 9     }
10     public void push(int element) {
11         // write your code here
12         stack1.push(element);
13     }
14 
15     public int pop() {
16         // write your code here
17         if (stack2.isEmpty()) {
18             while (!stack1.isEmpty()) {
19                 stack2.push(stack1.pop());
20             }
21         }
22         if (stack2.isEmpty()) {
23             return 0;
24         }
25         return stack2.pop();
26     }
27 
28     public int top() {
29         // write your code here
30         if (stack2.isEmpty()) {
31             while (!stack1.isEmpty()) {
32                 stack2.push(stack1.pop());
33             }
34         }
35         if (stack2.isEmpty()) {
36             return 0;
37         }
38         return stack2.peek();
39     }
40 }
View Code

 

面试题8 -- 寻找旋转排序数组中的最小值

假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。

你需要找到其中最小的元素。

你可以假设数组中不存在重复的元素。

 1 public class Solution {
 2     /**
 3      * @param nums: a rotated sorted array
 4      * @return: the minimum number in the array
 5      */
 6     public int findMin(int[] nums) {
 7         // write your code here
 8         if (nums == null || nums.length == 0) {
 9             return 0;
10         }
11         int start = 0;
12         int end = nums.length - 1;
13         int mid = start;
14         while (nums[start] > nums[end]) {
15             if (end - start == 1) {
16                 mid = end;
17                 break;
18             }
19             mid = start + (end - start) / 2;
20             if (nums[mid] > nums[start]) {
21                 start = mid;
22             } else if (nums[mid] < nums[end]) {
23                 end = mid;
24             }
25         }
26         return nums[mid];
27     }
28 }
View Code

 

 1 public class Solution {
 2     /*
 3      * @param nums: a rotated sorted array
 4      * @return: the minimum number in the array
 5      */
 6     public int findMin(int[] nums) {
 7         // write your code here
 8         if (nums == null || nums.length == 0) {
 9             return -1;
10         }
11         int start = 0, end = nums.length - 1;
12         int target = nums[nums.length - 1];
13         while (start + 1 < end) {
14             int mid = start + (end - start) / 2;
15             if (nums[mid] > target) {
16                 start = mid;
17             } else {
18                 end = mid;
19             }
20         }
21         if (nums[start] > nums[end]) {
22             return nums[end];
23         } else {
24             return nums[start];
25         }
26     }
27 }
View Code

 

 1 public class Solution {
 2     /*
 3      * @param nums: a rotated sorted array
 4      * @return: the minimum number in the array
 5      */
 6     public int findMin(int[] nums) {
 7         // write your code here
 8         if (nums == null || nums.length == 0) {
 9             return -1;
10         }
11         int start = 0, end = nums.length - 1;
12         while (start + 1 < end) {
13             int mid = start + (end - start) / 2;
14             if (nums[mid] > nums[end]) {
15                 start = mid;
16             } else {
17                 end = mid;
18             }
19         }
20         if (nums[start] > nums[end]) {
21             return nums[end];
22         }
23         return nums[start];
24     }
25 }
View Code

 

拓展 -- 寻找旋转排序数组中的最小值 II

假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。

你需要找到其中最小的元素。

数组中可能存在重复的元素。

 1 public class Solution {
 2     /**
 3      * @param num: a rotated sorted array
 4      * @return: the minimum number in the array
 5      */
 6     public int findMin(int[] num) {
 7         // write your code here
 8         if (num == null || num.length == 0) {
 9             return 0;
10         }
11         int start = 0;
12         int end = num.length - 1;
13         int mid = start;
14         while (num[start] >= num[end]) {
15             if (end - start == 1) {
16                 mid = end;
17                 break;
18             }
19             mid = start + (end - start) / 2;
20             if (num[start] == num[mid] && num[mid] == num[end]) {
21                 return findMinInOrder(num, start, end);
22             }
23             if (num[mid] >= num[start]) {
24                 start = mid;
25             } else if (num[mid] <= num[end]) {
26                 end = mid;
27             }
28         }
29         return num[mid];
30     }
31     public int findMinInOrder(int[] num, int start, int end) {
32         int result = num[start];
33         for (int i = start + 1; i <= end; i++) {
34             if (num[i] < result) {
35                 result = num[i];
36                 break;
37             }
38         }
39         return result;
40     }
41 }
View Code

 

 1 public class Solution {
 2     /*
 3      * @param nums: a rotated sorted array
 4      * @return: the minimum number in the array
 5      */
 6     public int findMin(int[] nums) {
 7         // write your code here
 8         if (nums == null || nums.length == 0) {
 9             return -1;
10         }
11         int start = 0, end = nums.length - 1;
12         while (start + 1 < end) {
13             int mid = start + (end - start) / 2;
14             if (nums[mid] == nums[end]) {
15                 end--;
16             } else if (nums[mid] > nums[end]) {
17                 start = mid;
18             } else {
19                 end = mid;
20             }
21         }
22         if (nums[start] > nums[end]) {
23             return nums[end];
24         }
25         return nums[start];
26     }
27 }
View Code

 

面试题14 -- 奇偶分割数组

分割一个整数数组,使得奇数在前偶数在后

思路:前后指针,前指针找到偶数,后指针找到奇数,交换。

 1 public class Solution {
 2     /*
 3      * @param nums: an array of integers
 4      * @return: nothing
 5      */
 6     public void partitionArray(int[] nums) {
 7         // write your code here
 8         if (nums == null || nums.length <= 1) {
 9             return;
10         }
11         int start = 0, end = nums.length - 1;
12         while (start < end) {
13             while (start < end && (nums[start] & 1) == 1) {
14                 start++;
15             }
16             while (start < end && (nums[end] & 1) == 0) {
17                 end--;
18             }
19             if (start < end) {
20                 int temp = nums[start];
21                 nums[start] = nums[end];
22                 nums[end] = temp;
23                 start++;
24                 end--;
25             }
26         }
27     }
28 }
View Code

 

 

面试题11 -- 快速幂

计算a ^ n % b,其中a,b和n都是32位的整数。

 1 class Solution {
 2     /*
 3      * @param a, b, n: 32bit integers
 4      * @return: An integer
 5      */
 6     public int fastPower(int a, int b, int n) {
 7         // write your code here
 8         if (n == 0) {
 9             return 1 % b;
10         }
11         if (n == 1) {
12             return a % b;
13         }
14         long product = fastPower(a, b, n >> 1);
15         product = (product * product) % b;
16         if ((n & 1) != 0) {
17             product = (product * a) % b;
18         }
19         return (int) product;
20     }
21 }
View Code

 

面试题12 -- 用递归打印数字

用递归的方法找到从1到最大的N位整数。

 1 public class Solution {
 2     /**
 3      * @param n: An integer.
 4      * return : An array storing 1 to the largest number with n digits.
 5      */
 6     public List<Integer> numbersByRecursion(int n) {
 7         // write your code here
 8         List<Integer> results = new ArrayList<Integer>();
 9         dfsHelper(results, n, 0);
10         return results;
11     }
12     public void dfsHelper(List<Integer> results, int n, int sum) {
13         if (n == 0) {
14             if (sum != 0) {
15                 results.add(sum);
16             }
17             return ;
18         }
19         for (int i = 0; i < 10; i++) {
20             dfsHelper(results, n - 1, sum * 10 + i);
21         }
22     }
23 }
View Code

 

面试题13 -- 在O(1)时间复杂度删除链表节点

给定一个单链表中的一个等待被删除的节点(非表头或表尾)。请在在O(1)时间复杂度删除该链表节点。

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param node: the node in the list should be deleted
15      * @return: nothing
16      */
17     public void deleteNode(ListNode node) {
18         // write your code here
19         if (node == null) {
20             return;
21         }
22         node.val = node.next.val;
23         node.next = node.next.next;
24     }
25 }
View Code

 

面试题15 -- 删除链表中倒数第n个节点

给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。

注意事项:链表中的节点个数大于等于n(代码对n输入不合法也判断了,鲁棒性更好)
 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param head: The first node of linked list.
15      * @param n: An integer.
16      * @return: The head of linked list.
17      */
18     ListNode removeNthFromEnd(ListNode head, int n) {
19         // write your code here
20         if (head == null || n <= 0) {
21             return head;
22         }
23         ListNode fakeHead = new ListNode(0);
24         fakeHead.next = head;
25         ListNode ahead = fakeHead;
26         for (int i = 0; i < n; i++) {
27             if (ahead.next != null) {
28                 ahead = ahead.next;
29             } else {
30                 return head;
31             }
32         }
33         ListNode behind = fakeHead;
34         while (ahead.next != null) {
35             ahead = ahead.next;
36             behind = behind.next;
37         }
38         behind.next = behind.next.next;
39         return fakeHead.next;
40     }
41 }
View Code

 

面试题17 -- 合并两个排序链表

将两个排序链表合并为一个新的排序链表

方法一:递归

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param ListNode l1 is the head of the linked list
15      * @param ListNode l2 is the head of the linked list
16      * @return: ListNode head of linked list
17      */
18     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
19         // write your code here
20         if (l1 == null) {
21             return l2;
22         }
23         if (l2 == null) {
24             return l1;
25         }
26         ListNode head = null;
27         if (l1.val < l2.val) {
28             head = l1;
29             head.next = mergeTwoLists(l1.next, l2);
30         } else {
31             head = l2;
32             head.next = mergeTwoLists(l1, l2.next);
33         }
34         return head;
35     }
36 }
View Code

方法二:循环

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param ListNode l1 is the head of the linked list
15      * @param ListNode l2 is the head of the linked list
16      * @return: ListNode head of linked list
17      */
18     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
19         // write your code here
20         if (l1 == null) {
21             return l2;
22         }
23         if (l2 == null) {
24             return l1;
25         }
26         ListNode fakeHead = new ListNode(0);
27         ListNode cur = fakeHead;
28         while (l1 != null || l2 != null) {
29             ListNode newNode = new ListNode(0);
30             if (l1 != null && l2 != null) {
31                 if (l1.val < l2.val) {
32                     newNode.val = l1.val;
33                     l1 = l1.next;
34                 } else {
35                     newNode.val = l2.val;
36                     l2 = l2.next;
37                 }
38             } else if (l1 != null && l2 == null) {
39                 newNode.val = l1.val;
40                 l1 = l1.next;
41             } else {
42                 newNode.val = l2.val;
43                 l2 = l2.next;
44             }
45             cur.next = newNode;
46             cur = cur.next;
47         }
48         cur.next = null;
49         return fakeHead.next;
50     }
51 }
View Code

 

面试题18 -- 子树

有两个不同大小的二进制树: T1 有上百万的节点; T2有好几百的节点。请设计一种算法,判定 T2 是否为 T1的子树。

注意事项:若 T1 中存在从节点 n 开始的子树与 T2 相同,我们称 T2 是 T1 的子树。也就是说,如果在 T1 节点 n 处将树砍断,砍断的部分将与 T2 完全相同。

变形 -- 求子结构,此时整体思路一样,只需要把逻辑判断改一下,具体看程序中的注释。

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param T1, T2: The roots of binary tree.
15      * @return: True if T2 is a subtree of T1, or false.
16      */
17     public boolean isSubtree(TreeNode T1, TreeNode T2) {
18         // write your code here
19         if (T2 == null) {
20             return true;
21         }
22         boolean result = false;
23         if (T1 != null && T2 != null) {
24             if (T1.val == T2.val) {
25                 result = isT1HasT2(T1, T2);
26             }
27             if (!result) {
28                 result = isSubtree(T1.left, T2);
29             }
30             if (!result) {
31                 result = isSubtree(T1.right, T2);
32             }
33         }
34         return result;
35     }
36     public boolean isT1HasT2(TreeNode T1, TreeNode T2) {
37         //注意如果题目换成判断是否为树的子结构的话,只需改一下此处的逻辑判断,即当T1 != null && T2 == null时要return true而不是false,即改成如下代码:
38         //  if (T2 == null) {
39         //      return true;
40         //  }
41         //  if (T1 == null) {
42         //      retrun false;
43         //  }
44        if (T1 == null && T2 == null) {
45            return true;
46        } else if (T1 == null || T2 == null) {
47            return false;
48        }
49        //接下来步骤一样
50        if (T1.val != T2.val) {
51            return false;
52        }
53        return isT1HasT2(T1.left, T2.left) && isT1HasT2(T1.right, T2.right);
54     }
55 }
View Code

 

面试题20 -- 螺旋矩阵

给定一个包含 m x n 个要素的矩阵,(m 行, n 列),按照螺旋顺序,返回该矩阵中的所有要素。

注意此题打印矩阵一圈的分析思路,首先至少一行,直接打印;然后必须至少两行才能打印最右边的列,必须两行两列才能打印最下面的行,必须三行两列才能打印最左边的列。

 1 public class Solution {
 2     /**
 3      * @param matrix a matrix of m x n elements
 4      * @return an integer list
 5      */
 6     public List<Integer> spiralOrder(int[][] matrix) {
 7         // Write your code here
 8         List<Integer> result = new ArrayList<Integer>();
 9         if (matrix == null || matrix.length == 0) {
10             return result;
11         }
12         int m = matrix.length;
13         int n = matrix[0].length;
14         int start = 0;
15         int endM = m - 1;
16         int endN = n - 1;
17         while (m > start * 2 && n > start * 2) {
18             endM = m - 1 - start;
19             endN = n - 1 - start;
20             printMatrixInCircle(matrix, start, endM, endN, result);
21             start++;
22         }
23         return result;
24     }
25     public void printMatrixInCircle(int[][] matrix, int start,
26                         int endM, int endN, List<Integer> result) {
27         for (int i = start; i <= endN; i++) {
28             result.add(matrix[start][i]);
29         }
30         if (endM > start) {
31             for (int i = start + 1; i <= endM; i++) {
32                 result.add(matrix[i][endN]);
33             }
34         }
35         if (endM > start && endN > start) {
36             for (int i = endN - 1; i >= start; i--) {
37                 result.add(matrix[endM][i]);
38             }
39         }
40         if (endM > start + 1 && endN > start) {
41             for (int i = endM - 1; i > start; i--) {
42                 result.add(matrix[i][start]);
43             }
44         }
45     }
46 }
View Code

自己写的容易理解的解法

 1 public class Solution {
 2     /*
 3      * @param matrix: a matrix of m x n elements
 4      * @return: an integer list
 5      */
 6     public List<Integer> spiralOrder(int[][] matrix) {
 7         // write your code here
 8         List<Integer> result = new ArrayList<>();
 9         if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
10             return result;
11         }
12         int n = matrix.length, m = matrix[0].length;
13         int startN = 0, endN = n - 1, startM = 0, endM = m - 1;
14         while (startN <= endN && startM <= endM) {
15             for (int i = startM; i <= endM; i++) {
16                 result.add(matrix[startN][i]);
17             }
18             if (endN > startN)  {
19                 for (int i = startN + 1; i <= endN; i++) {
20                     result.add(matrix[i][endM]);
21                 }
22             }
23             if (endN > startN && endM > startM) {
24                 for (int i = endM - 1; i >= startM; i--) {
25                     result.add(matrix[endN][i]);
26                 }
27             }
28             if (endN - startN >= 2 && endM > startM) {
29                 for (int i = endN - 1; i >= startN + 1; i--) {
30                     result.add(matrix[i][startM]);
31                 }
32             }
33             startN++;
34             startM++;
35             endN--;
36             endM--;
37         }
38         return result;
39     }
40 }
View Code

 

拓展 -- Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

Given n = 3,
You should return the following matrix:
[
  [ 1, 2, 3 ],
  [ 8, 9, 4 ],
  [ 7, 6, 5 ]
]
题目
 1 public class Solution {
 2     /**
 3      * @param n an integer
 4      * @return a square matrix
 5      */
 6     public int[][] generateMatrix(int n) {
 7         // Write your code here
 8         if (n < 0) {
 9             return null;
10         }
11         int[][] result = new int[n][n];
12         int xStart = 0;
13         int yStart = 0;
14         int num = 1;
15         while (n > 0) {
16             if (n == 1) {
17                 result[xStart][yStart] = num++;
18                 break;
19             }
20             for (int i = 0; i < n - 1; i++) {
21                 result[xStart][yStart + i] = num++;
22             }
23             for (int i = 0; i < n - 1; i++) {
24                 result[xStart + i][yStart + n - 1] = num++;
25             }
26             for (int i = 0; i < n - 1; i++) {
27                 result[xStart + n - 1][yStart + n - 1 - i] = num++;
28             }
29             for (int i = 0; i < n - 1; i++) {
30                 result[xStart + n - 1 - i][yStart] = num++;
31             }
32             xStart++;
33             yStart++;
34             n -= 2;
35         }
36         return result;
37     }
38 }
View Code
 1 public class Solution {
 2     public int[][] generateMatrix(int n) {
 3         if (n <= 0) {
 4             return new int[0][0];
 5         }
 6         int[][] matrix = new int[n][n];
 7         for (int i = 0; n > 2 * i; i++) {
 8             copyOneCircle(matrix, i);
 9         }
10         return matrix;
11     }
12     public void copyOneCircle(int[][] matrix, int start) {
13         int n = matrix.length;
14         int rows = n - 2 * start;
15         int columns = n - 2 * start;
16         int num = 0;
17         if (start == 0) {
18             num = 1;
19         } else {
20             num = matrix[start - 1][start - 1] + 4 * (rows + 1);
21         }
22         if (rows >= 1) {
23             for (int i = start; i <= n - 1 - start; i++) {
24                 matrix[start][i] = num++;
25             }
26         }
27         if (rows >= 2) {
28             for (int i = start + 1; i <= n - 1 - start; i++) {
29                 matrix[i][n - 1 - start] = num++;
30             }
31         }
32         if (rows >= 2 && columns >= 2) {
33             for (int i = n - 2 - start; i >= start; i--) {
34                 matrix[n - 1 - start][i] = num++;
35             }
36         }
37         if (rows >= 3 && columns >= 2) {
38             for (int i = n - 2 - start; i >= start + 1; i--) {
39                 matrix[i][start] = num++;
40             }
41         }
42     }
43 }
View Code

 自己写的容易理解的解法

 1 public class Solution {
 2     /*
 3      * @param n: An integer
 4      * @return: a square matrix
 5      */
 6     public int[][] generateMatrix(int n) {
 7         // write your code here
 8         int[][] matrix = new int[n][n];
 9         if (n <= 0) {
10             return matrix;
11         }
12         int start = 0, end = n - 1;
13         int count = 1;
14         for (start = 0; start <= (n + 1) / 2; start++, end--) {
15             for (int i = start; i <= end; i++) {
16                 matrix[start][i] = count;
17                 count++;
18             }
19             if (end > start) {
20                 for (int i = start + 1; i <= end; i++) {
21                     matrix[i][end] = count;
22                     count++;
23                 }
24             }
25             if (end > start) {
26                 for (int i = end - 1; i >= start; i--) {
27                     matrix[end][i] = count;
28                     count++;
29                 }
30             }
31             if (end > start && end > start + 1) {
32                 for (int i = end - 1; i >= start + 1; i--) {
33                     matrix[i][start] = count;
34                     count++;
35                 }
36             }
37         }
38         return matrix;
39     }
40 }
View Code

 

 

面试题36 -- 数组中的逆序对

题目:数组中前一个数字大于后一个数字则这两个数字构成一个逆序对,统计数组中所有的逆序对个数。

思路:暴力算法两个指针便利整个数组求得,时间复杂度O(n^2),空间复杂度O(1)。

   换一种思路,归并排序,注意复制到temp数组中是从后往前复制,如果前一个数组元素大于后一个,count加上有一个数组相应位置开始到其开始位置的元素个数,然后继续。求子数组内部的逆序对有可以递归的求两个子子数组之间的逆序对个数。时间复杂度即为归并排序的时间复杂度O(nlogn),空间复杂度O(n)。O(n)空间换时间效率。

 1 public class Solution {
 2     /**
 3      * @param A an array
 4      * @return total of reverse pairs
 5      */
 6     public long reversePairs(int[] A) {
 7         // Write your code here
 8         long count = 0;
 9         if (A == null || A.length == 0) {
10             return count;
11         }
12         return mergeSort(A, new int[A.length], 0, A.length - 1);
13     }
14     public int mergeSort(int[] A, int[] temp, int start, int end) {
15         if (start == end) {
16             return 0;
17         }
18         int count = 0;
19         int mid = start + (end - start) / 2;
20         int leftCount = mergeSort(A, temp, start, mid);
21         int rightCount = mergeSort(A, temp, mid + 1, end);
22         int left = mid;
23         int right = end;
24         int indexTemp = end;
25         while (left >= start && right >= mid + 1) {
26             if (A[left] > A[right]) {
27                 count += right - mid;
28                 temp[indexTemp--] = A[left];
29                 left--;
30             } else {
31                 temp[indexTemp--] = A[right];
32                 right--;
33             }
34         }
35         while (left >= start) {
36             temp[indexTemp--] = A[left--];
37         }
38         while (right >= mid + 1) {
39             temp[indexTemp--] = A[right--];
40         }
41         for (int i = start; i <= end; i++) {
42             A[i] = temp[i];
43         }
44         return leftCount + rightCount + count;
45     }
46 }
View Code

 

面试题64 -- 数据流中位数

思路I:建立一个大根堆和一个小根堆,分别来存储前半部分和后半部分的数据,最后返回大根堆的堆顶元素即可。设立一个计数器,偶数的时候加入大根堆,加入过程中注意所加入的值比小根堆堆顶元素大的话就吧该数插入到小根堆,小根堆堆顶元素加入到大根堆。奇数的时候加入小根堆,加入过程同上。

 

数字是不断进入数组的,在每次添加一个新的数进入数组的同时返回当前新数组的中位数。
中位数的定义:
中位数是排序后数组的中间值,如果有数组中有n个数,则中位数为A[(n-1)/2]。
比如:数组A=[1,2,3]的中位数是2,数组A=[1,19]的中位数是1。
样例
持续进入数组的数的列表为:[1, 2, 3, 4, 5],则返回[1, 1, 2, 2, 3]
持续进入数组的数的列表为:[4, 5, 1, 3, 2, 6, 0],则返回 [4, 4, 4, 3, 3, 3, 3]
持续进入数组的数的列表为:[2, 20, 100],则返回[2, 2, 20]
题目
 1 public class Solution {
 2     public int count = 0;
 3     PriorityQueue<Integer> maxHeap;
 4     PriorityQueue<Integer> minHeap;
 5     /**
 6      * @param nums: A list of integers.
 7      * @return: the median of numbers
 8      */
 9     public int[] medianII(int[] nums) {
10         // write your code here
11         if (nums == null || nums.length == 0) {
12             return new int[0];
13         }
14         int[] result = new int[nums.length];
15         maxHeap = new PriorityQueue<Integer>(nums.length,
16             new Comparator<Integer>() {
17                 public int compare(Integer a, Integer b) {
18                     return b - a;
19             }
20         });
21         minHeap = new PriorityQueue<Integer>();
22         for (int i = 0; i < nums.length; i++) {
23             addNumber(nums[i]);
24             result[i] = maxHeap.peek();
25         }
26         return result;
27     }
28     public void addNumber(int number) {
29         if (count % 2 == 0) {
30             if (minHeap.size() == 0
31                 || minHeap.size() > 0 && number <= minHeap.peek()) {
32                 maxHeap.offer(number);
33             } else {
34                 minHeap.offer(number);
35                 maxHeap.offer(minHeap.poll());
36             }
37         } else {
38             if (maxHeap.size() == 0
39                 || maxHeap.size() > 0 && number >= maxHeap.peek()) {
40                 minHeap.offer(number);
41             } else {
42                 maxHeap.offer(number);
43                 minHeap.offer(maxHeap.poll());
44             }
45         }
46         count++;
47     }
48 }
View Code

思路II:同样建立大根堆和小根堆,但是不用计数器。每次加入元素分两种情况调整:minHeap.size() > maxHeap.size()和maxHeap.size() > minHeap.size() + 1。这种写法更简洁,推荐此种写法。

 1 public class Solution {
 2     public int count = 0;
 3     PriorityQueue<Integer> maxHeap;
 4     PriorityQueue<Integer> minHeap;
 5     /**
 6      * @param nums: A list of integers.
 7      * @return: the median of numbers
 8      */
 9     public int[] medianII(int[] nums) {
10         // write your code here
11         if (nums == null || nums.length == 0) {
12             return new int[0];
13         }
14         int[] result = new int[nums.length];
15         PriorityQueue<Integer> maxHeap = new PriorityQueue<>(nums.length, Collections.reverseOrder());
16         PriorityQueue<Integer> minHeap = new PriorityQueue<>();
17         for (int i = 0; i < nums.length; i++) {
18             if (maxHeap.isEmpty() || nums[i] < maxHeap.peek()) {
19                 maxHeap.offer(nums[i]);
20             } else {
21                 minHeap.offer(nums[i]);
22             }
23             if (minHeap.size() > maxHeap.size()) {
24                 maxHeap.offer(minHeap.poll());
25             }
26             if (maxHeap.size() > minHeap.size() + 1) {
27                 minHeap.offer(maxHeap.poll());
28             }
29             result[i] = maxHeap.peek();
30         }
31         return result;
32     }
33 }
View Code

Follow Up -- 滑动窗口中位数(Sliding Window Median

Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, find the median of the element inside the window at each moving. (If there are even numbers in the array, return the N/2-th number after sorting the element in the window. )

Example
For array [1,2,7,8,5], moving window size k = 3. return [2,7,7]

At first the window is at the start of the array like this

[ | 1,2,7 | ,8,5] , return the median 2;

then the window move one step forward.

[1, | 2,7,8 | ,5], return the median 7;

then the window move one step forward again.

[1,2, | 7,8,5 | ], return the median 7;

思路:做法类似,但是要注意加入元素和删除元素都要进行两种情况调整!

 1 public class Solution {
 2     /**
 3      * @param nums: A list of integers.
 4      * @return: The median of the element inside the window at each moving.
 5      */
 6     public ArrayList<Integer> medianSlidingWindow(int[] nums, int k) {
 7         // write your code here
 8         ArrayList<Integer> result = new ArrayList<>();
 9         if (nums == null || nums.length == 0 || k <= 0 || k > nums.length) {
10             return result;
11         }
12         PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, Collections.reverseOrder());
13         PriorityQueue<Integer> minHeap = new PriorityQueue<>();
14         for (int i = 0; i < nums.length; i++) {
15             if (maxHeap.isEmpty() || nums[i] <= maxHeap.peek()) {
16                 maxHeap.offer(nums[i]);
17             } else {
18                 minHeap.offer(nums[i]);
19             }
20             if (minHeap.size() > maxHeap.size()) {
21                 maxHeap.offer(minHeap.poll());
22             }
23             if (maxHeap.size() > minHeap.size() + 1) {
24                 minHeap.offer(maxHeap.poll());
25             }
26             if (i >= k - 1) {
27                 result.add(maxHeap.peek());
28                 if (nums[i - k + 1] <= maxHeap.peek()) {
29                     maxHeap.remove(nums[i - k + 1]);
30                 } else {
31                     minHeap.remove(nums[i - k + 1]);
32                 }
33                 if (minHeap.size() > maxHeap.size()) {
34                     maxHeap.offer(minHeap.poll());
35                 }
36                 if (maxHeap.size() > minHeap.size() + 1) {
37                     minHeap.offer(maxHeap.poll());
38                 }
39             }
40         }
41         return result;
42     }
43 }
View Code

 

面试题33 -- 把数组排成最小的数

给定一个整数数组,请将其重新排序,以构造最小值。
给定 [3, 32, 321],通过将数组重新排序,可构造 6 个可能性数字:

3+32+321=332321
3+321+32=332132
32+3+321=323321
32+321+3=323213
321+3+32=321332
321+32+3=321323
其中,最小值为 321323,所以,将数组重新排序后,该数组变为 [321, 32, 3]。
题目

思路:注意此题实际上是定义两个数的排序规则,不再是两个数的数值大小的排序规则。规定两个数字a,b组成的数ab < ba时a < b。注意拼接成ab可能ab会有溢出,因此用String来存放。注意去掉前缀"0"。

 1 public class Solution {
 2     /**
 3      * @param nums n non-negative integer array
 4      * @return a string
 5      */
 6     public String minNumber(int[] nums) {
 7         // Write your code here
 8         if (nums == null || nums.length == 0) {
 9             return null;
10         }
11         String[] temp = new String[nums.length];
12         for (int i = 0; i < nums.length; i++) {
13             temp[i] = String.valueOf(nums[i]);
14         }
15         Comparator<String> cmp = new Comparator<String>() {
16             public int compare(String s1, String s2) {
17                 String a = s1.concat(s2);
18                 String b = s2.concat(s1);
19                 return a.compareTo(b);
20             }
21         };
22         Arrays.sort(temp, cmp);
23         StringBuilder sb = new StringBuilder();
24         for (int i = 0; i < nums.length; i++) {
25             sb.append(temp[i]);
26         }
27         String s = sb.toString();
28         int i = 0;
29         for (i = 0; i < s.length(); i++) {
30             if (s.charAt(i) != '0') {
31                 break;
32             }
33         }
34         if (i == s.length()) {
35             return "0";
36         }
37         return s.substring(i);
38     }
39 }
View Code

 

面试题32 -- 统计数字

统计数字
计算数字k在0到n中的出现的次数,k可能是0~9的一个值

样例
例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次 (1, 10, 11, 12

暴力解法:若每一位为O(lonn),则时间复杂度为O(nlogn)。依次统计每一个数的0的个数。

 1 class Solution {
 2     /*
 3      * param k : As description.
 4      * param n : As description.
 5      * return: An integer denote the count of digit k in 1..n
 6      */
 7     public int digitCounts(int k, int n) {
 8         // write your code here
 9         if (k < 0 || k > 9 || n < 0) {
10             return 0;
11         }
12         int count = 0;
13         for (int i = 0; i <= n; i++) {
14             count += singleCount(k, i);
15         }
16         return count;
17     }
18     public int singleCount(int k, int num) {
19         if (k == 0 && num == 0) {
20             return 1;
21         }
22         int count = 0;
23         while (num != 0) {
24             if (num % 10 == k) {
25                 count++;
26             }
27             num = num / 10;
28         }
29         return count;
30     }
31 }
View Code

 

优雅解法:此解法只使用k取1 - 9的情况,因此k取0的情况单独采用暴力法来处理,注意同时k=0和n=0的特殊情况处理,返回1而不是0。

k = 1 - 9情况处理如下:

当某一位的数字小于i时,那么该位出现i的次数为:更高位数字x当前位数
当某一位的数字等于i时,那么该位出现i的次数为:更高位数字x当前位数+低位数字+1
当某一位的数字大于i时,那么该位出现i的次数为:(更高位数字+1)x当前位数
 1 class Solution {
 2     /*
 3      * param k : As description.
 4      * param n : As description.
 5      * return: An integer denote the count of digit k in 1..n
 6      */
 7     public int digitCounts(int k, int n) {
 8         // write your code here
 9         if (k < 0 || k > 9 || n < 0) {
10             return 0;
11         }
12         if (k == 0) {
13             return boundaryCount(k, n);
14         }
15         return generalCount(k, n);
16     }
17     public int boundaryCount(int k, int n) {
18         int count = 0;
19         for (int i = 0; i <= n; i++) {
20             count += singleCount(k, i);
21         }
22         return count;
23     }
24     public int singleCount(int k, int num) {
25         if (k == 0 && num == 0) {
26             return 1;
27         }
28         int count = 0;
29         while (num != 0) {
30             if (num % 10 == 0) {
31                 count++;
32             }
33             num = num / 10;
34         }
35         return count;
36     }
37     public int generalCount(int k, int n) {
38         int count = 0;
39         int low = 0;
40         int cur = 0;
41         int high = 0;
42         int factor = 1;
43         while (n / factor != 0) {
44             low = n - (n / factor) * factor;
45             cur = (n / factor) % 10;
46             high = n / (factor * 10);
47             if (cur < k) {
48                 count += high * factor;
49             } else if (cur == k) {
50                 count += high * factor + low + 1;
51             } else {
52                 count += (high + 1) * factor;
53             }
54             factor *= 10;
55         }
56         return count;
57     }
58 }
View Code

 

面试题29 -- 数组中出现次数超过一半的数字

给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。

注意事项
You may assume that the array is non-empty and the majority number always exist in the array.

样例
给出数组[1,1,1,1,2,2,2],返回 1

思路:遍历数组时保存两个值:数组中的数字和次数,每遍历一个数,如果和保存数字相同,次数+1,否则次数减1,当次数为0就保存当前数字,并且次数置为1,最后保留下来的数字即为所求。

 1 public class Solution {
 2     /**
 3      * @param nums: a list of integers
 4      * @return: find a  majority number
 5      */
 6     public int majorityNumber(ArrayList<Integer> nums) {
 7         // write your code
 8         if (nums == null || nums.size() == 0) {
 9             return -1;
10         }
11         int candidate = 0;
12         int count = 0;
13         for (int i = 0; i < nums.size(); i++) {
14             if (count == 0) {
15                 candidate = nums.get(i);
16                 count = 1;
17             } else if (candidate == nums.get(i)) {
18                 count++;
19             } else {
20                 count--;
21             }
22         }
23         return candidate;
24     }
25 }
View Code

拓展I:

给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一。

注意事项
数组中只有唯一的主元素

样例
给出数组[1,2,1,2,1,3,3] 返回 1

思路:三三抵销法,但是也有需要注意的地方:

1. 我们对cnt1,cnt2减数时,相当于丢弃了3个数字(当前数字,candidate1, candidate2)。也就是说,每一次丢弃数字,我们是丢弃3个不同的数字。

而Majority number超过了1/3所以它最后一定会留下来。

设定总数为N, majority number次数为m。丢弃的次数是x。则majority 被扔的次数是x

而m > N/3, N - 3x > 0. 

3m > N,  N > 3x 所以 3m > 3x, m > x 也就是说 m一定没有被扔完

最坏的情况,Majority number每次都被扔掉了,但它一定会在n1,n2中。

2. 为什么最后要再检查2个数字呢(从头开始统计,而不用剩下的count1, count2)?因为数字的编排可以让majority 数被过度消耗,使其计数反而小于n2,或者等于n2.前面举的例子即是。

另一个例子:1 1 1 1 2 3 2 3 4 4 4 这个 1就会被消耗过多,最后余下的反而比4少。

 1 public class Solution {
 2     /**
 3      * @param nums: A list of integers
 4      * @return: The majority number that occurs more than 1/3
 5      */
 6     public int majorityNumber(ArrayList<Integer> nums) {
 7         // write your code
 8         if (nums == null || nums.size() == 0) {
 9             return 0;
10         }
11         int candidate1 = 0;
12         int candidate2 = 0;
13         int count1 = 0;
14         int count2 = 0;
15         for (int i = 0; i < nums.size(); i++) {
16             int temp = nums.get(i);
17             if (count1 == 0) {
18                 candidate1 = temp;
19                 count1 = 1;
20             } else if (candidate1 == temp) {
21                 count1++;
22             }
23             if (count2 == 0 && temp != candidate1) {
24                 candidate2 = temp;
25                 count2 = 1;
26             } else if (candidate2 == temp) {
27                 count2++;
28             }
29             if (candidate1 != temp && candidate2 != temp) {
30                 count1--;
31                 count2--;
32             }
33         }
34         count1 = 0;
35         count2 = 0;
36         for (int i = 0; i < nums.size(); i++) {
37             if (candidate1 == nums.get(i)) {
38                 count1++;
39             }
40             if (candidate2 == nums.get(i)) {
41                 count2++;
42             }
43         }
44         if (count1 > count2) {
45             return candidate1;
46         }
47         return candidate2;
48     }
49 }
View Code 

自己写的易于理解的解法,跟前面的面试题29的程序结构类似。注意最后不能根据剩下的count1和count2的个数来确定,因为超过1 / 3的数的个数可能提前被消耗的过多。要重新遍历集合统计出两个侯选数candidate1和candidate2的次数才能决定。 

 1 public class Solution {
 2     /*
 3      * @param nums: a list of integers
 4      * @return: The majority number that occurs more than 1/3
 5      */
 6     public int majorityNumber(List<Integer> nums) {
 7         // write your code here
 8         if (nums == null || nums.size() == 0) {
 9             return 0;
10         }
11         int candidate1 = 0, candidate2 = 0;
12         int count1 = 0, count2 = 0;
13         for (int i = 0; i < nums.size(); i++) {
14             if (count1 == 0) {
15                 candidate1 = nums.get(i);
16                 count1 = 1;
17             } else if (candidate1 == nums.get(i)) {
18                 count1++;
19             } else if (count2 == 0) {
20                 candidate2 = nums.get(i);
21                 count2 = 1;
22             } else if (candidate2 == nums.get(i)) {
23                 count2++;
24             } else {
25                 count1--;
26                 count2--;
27             }
28         }
29         count1 = 0;
30         count2 = 0;
31         for (int i = 0; i < nums.size(); i++) {
32             if (nums.get(i) == candidate1) {
33                 count1++;
34             } else if (nums.get(i) == candidate2) {
35                 count2++;
36             }
37         }
38         if (count1 > count2) {
39             return candidate1;
40         }
41         return candidate2;
42     }
43 }
View Code

 

 

拓展II

给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的1/k。

注意事项

数组中只有唯一的主元素

样例
给出数组 [3,1,2,3,2,3,3,4,4,4] ,和 k = 3,返回 3

思路:与拓展一相同,只不过为了加快查找速度用HashMap存储数字和次数。注意:当次数为0时本次不能把新元素放进去!!!!!!要等下一轮方可放入新元素。

 1 public class Solution {
 2     /**
 3      * @param nums: A list of integers
 4      * @param k: As described
 5      * @return: The majority number
 6      */
 7     public int majorityNumber(ArrayList<Integer> nums, int k) {
 8         // write your code
 9         if (nums == null || nums.size() == 0 || k <= 1) {
10             return 0;
11         }
12         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
13         for (int i = 0; i < nums.size(); i++) {
14             
15             int temp = nums.get(i);
16             if (map.containsKey(temp)) {
17                 map.put(temp, map.get(temp) + 1);
18             }
19             if (!map.containsKey(temp) && map.size() < k - 1) {
20                 map.put(temp, 1);
21             }
22             if (!map.containsKey(temp) && map.size() == k - 1) {
23                 ArrayList<Integer> removeList = new ArrayList<>();
24                 for (int num : map.keySet()) {
25                     map.put(num, map.get(num) - 1);
26                     if (map.get(num) == 0) {
27                         removeList.add(num);
28                     }
29                 }
30                 for (Integer num : removeList) {
31                     map.remove(num);
32                 }
33             }
34         }
35         for (Integer key : map.keySet()) {
36             map.put(key, 0);
37         }
38         for (int i = 0; i < nums.size(); i++) {
39             int element = nums.get(i);
40             if (map.containsKey(element)) {
41                 map.put(element, map.get(element) + 1);
42             }
43         }
44         int maxCount = 0;
45         int maxKey = 0;
46         for (Integer key : map.keySet()) {
47             if (map.get(key) > maxCount) {
48                 maxCount = map.get(key);
49                 maxKey = key;
50             }
51         }
52         return maxKey;
53     }
54 }
View Code

 自己写的易于理解的解法,跟前面的面试题29的程序结构类似。

 1 public class Solution {
 2     /*
 3      * @param nums: A list of integers
 4      * @param k: An integer
 5      * @return: The majority number
 6      */
 7     public int majorityNumber(List<Integer> nums, int k) {
 8         // write your code here
 9         if (nums == null || nums.size() == 0 || k <= 1) {
10             return 0;
11         }
12         Map<Integer, Integer> map = new HashMap<>();
13         for (int i = 0; i < nums.size(); i++) {
14             int element = nums.get(i);
15             if (!map.containsKey(element) && map.size() < k - 1) {
16                 map.put(element, 1);
17             } else if (!map.containsKey(element) && map.size() == k - 1) {
18                 List<Integer> removeList = new ArrayList<>();
19                 for (int key : map.keySet()) {
20                     map.put(key, map.get(key) - 1);
21                     if (map.get(key) == 0) {
22                         removeList.add(key);
23                     }
24                 }
25                 for (int key : removeList) {
26                     map.remove(key);
27                 }
28             } else {
29                 map.put(element, map.get(element) + 1);
30             }
31         }
32         for (int key : map.keySet()) {
33             System.out.println(key);
34             map.put(key, 0);
35         }
36         for (int i = 0; i < nums.size(); i++) {
37             int element = nums.get(i);
38             if (map.containsKey(element)) {
39                 map.put(element, map.get(element) + 1);
40             }
41         }
42         int maxKey = 0;
43         int maxCount = 0;
44         for (int key : map.keySet()) {
45             if (map.get(key) > maxCount) {
46                 maxCount = map.get(key);
47                 maxKey = key;
48             }
49         }
50         return maxKey;
51     }
52 }
View Code

 

 

面试题47 -- 不用加减乘除做加法

A + B Problem

Write a function that add two numbers A and B. You should not use + or any arithmetic operators.

Are a and b both 32-bit integers?
Yes.

Can I use bit operation?
Sure you can.

Example
Given a=1 and b=2 return 3

思路:十进制加法准则应用到二进制,先不算进位的将二进制的每位相加,相加规则就是异或运算,0+0=0,1+1=0,0+1=1,1+0=0。同时记录下进位,进位的求得就是按位与并且左一,将不算进位的相加结果再和进位结果相加,依次循环,知道进位为0即可。

 1 class Solution {
 2     /*
 3      * param a: The first integer
 4      * param b: The second integer
 5      * return: The sum of a and b
 6      */
 7     public int aplusb(int a, int b) {
 8         // write your code here, try to do it without arithmetic operators.
 9         int sum = a ^ b;
10         int carry = (a & b) << 1;
11         while (carry != 0) {
12             a = sum;
13             b = carry;
14             sum = a ^ b;
15             carry = (a & b) << 1;
16         }
17         return sum;
18     }
19 }
View Code

 

面试题42 -- 翻转单词顺序

Reverse Words in a String

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
 1 public class Solution {
 2     /**
 3      * @param s : A string
 4      * @return : A string
 5      */
 6     public String reverseWords(String s) {
 7         // write your code
 8         if (s == null || s.length() == 0) {
 9             return "";
10         }
11         String[] strs = s.split(" ");
12         StringBuilder sb = new StringBuilder();
13         for (int i = strs.length - 1; i >= 0; i--) {
14             sb.append(strs[i]).append(" ");
15         }
16         if (sb.length() == 0) {
17             return "";
18         } else {
19             return sb.substring(0, sb.length() - 1);
20         }
21     }
22 }
View Code

 

面试题40 -- 数组中只出现一次的数字(Single Number)

Given 2*n + 1 numbers, every numbers occurs twice except one, find it.

Example
Given [1,2,2,1,3,4,3], return 4

思路:对数组中的每个元素做异或运算,同一个数字和它本省异或相抵消,最后的结果即为数组中只出现一次的数字。

 1 public class Solution {
 2     /**
 3       *@param A : an integer array
 4       *return : a integer
 5       */
 6     public int singleNumber(int[] A) {
 7         // Write your code here
 8         if (A == null || A.length == 0) {
 9             return 0;
10         }
11         int sum = 0;
12         for (int i = 0; i < A.length; i++) {
13             sum = sum ^ A[i];
14         }
15         return sum;
16     }
17 }
View Code

 

Follow Up I

Given 2*n + 2 numbers, every numbers occurs twice except two, find them.

Example
Given [1,2,2,3,4,4,5,3] return 1 and 5

思路:将问题转化为数组中只出现一次的数字问题,首先数组中每个元素异或,由于有两个不同的数字,最后结果一定不为0,也就是说结果的二进制表示中一定有一位为1,现在找出这一位,然后根据这一位是否为1将数组分成两个子数组,两个只出现一次的数字必然被分到两个不同子数组中,剩下成对出现的数字也是成对被分到某一子数组中,这样两个子数组每个子数组都含有只出现一次的数字和成对出现的数字,问题转化为求子数组中只出现一次的数字问题。得解。

 1 public class Solution {
 2     /**
 3      * @param A : An integer array
 4      * @return : Two integers
 5      */
 6     public List<Integer> singleNumberIII(int[] A) {
 7         // write your code here
 8         List<Integer> result = new ArrayList<>();
 9         if (A == null || A.length < 2) {
10             return result;
11         }
12         int num = 0;
13         for (int i = 0; i < A.length; i++) {
14             num ^= A[i];
15         }
16         int indexBit = 0;
17         for (int i = 0; i < 32; i++) {
18             if ((num & (1 << i)) != 0) {
19                 indexBit = i;
20                 break;
21             }
22         }
23         int num0 = 0;
24         int num1 = 0;
25         for (int i = 0; i < A.length; i++) {
26             if ((A[i] & (1 << indexBit)) != 0) {
27                 num1 ^= A[i];
28             } else {
29                 num0 ^= A[i];
30             }
31         }
32         result.add(num0);
33         result.add(num1);
34         return result;
35     }
36 }
View Code

 

Follow Up II

Given 3*n + 1 numbers, every numbers occurs triple times except one, find it.

Example
Given [1,1,2,3,3,3,2,2,4,1] return 4

思路:统计每个数字的对应二进制位上1的个数然后模3,余数即为只出现一次的数字的对应的二进制为的结果,由于是int,32位,循环32次即可。最后每一位的结果做或运算即可得到最后的结果。

同理,这个思路可以推广到k *n + 1问题,即数组中除了一个数字只出现一次,其余数字均出现k次(k >= 2)。

 1 public class Solution {
 2     /**
 3      * @param A : An integer array
 4      * @return : An integer
 5      */
 6     public int singleNumberII(int[] A) {
 7         // write your code here
 8         if (A == null || A.length == 0) {
 9             return 0;
10         }
11         int result = 0;
12         for (int i = 0; i < 32; i++) {
13             int sum = 0;
14             for (int j = 0; j < A.length; j++) {
15                 if ((A[j] & (1 << i)) != 0) {
16                     sum++;
17                 }
18             }
19             result |= (sum % 3) << i;
20         }
21         return result;
22     }
23 }
View Code

 

面试题49 -- 把字符串转换成整数

Implement function atoi to convert a string to an integer.

If no valid conversion could be performed, a zero value is returned.

If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Example
"10" => 10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1

 

思路:注意三点即可。1.字符串事先做trim()处理消除首位空格  2.首位为+或-的时候索引才加一,否则不加。相应地只有为-符号为才为-,其余为+。  3.注意Integer.MIN_VALUE情况的处理,由于我们是去掉符号算和,注意和sum定义为long型以处理溢出的情况,所以这种情况溢出但是实际上是不算做溢出的,应当返回原来的值Integer.MIN_VALUE而不是-Integer.MAX_VALUE。

 

 1 public class Solution {
 2     /**
 3      * @param str: A string
 4      * @return An integer
 5      */
 6     public int atoi(String str) {
 7         // write your code here
 8         if (str == null || str.length() == 0) {
 9             return 0;
10         }
11         str = str.trim();
12         boolean flag = true;
13         int start = 0;
14         //只有当第一位为+或者-start才加一,其余符号start统统从0开始!!!
15         if (str.charAt(0) == '-') {
16             flag = false;
17             start++;
18         } else if (str.charAt(0) == '+') {
19             start++;
20         }
21         long sum = 0;
22         while (start < str.length() && str.charAt(start) >= '0' && str.charAt(start) <= '9') {
23             sum = sum * 10 + str.charAt(start) - '0';
24             //为了处理"- 2 ^ 31 - 1"这种情况
25             if (sum > (long) Integer.MAX_VALUE + 1) {
26                 if (flag) {
27                     return Integer.MAX_VALUE;
28                 } else {
29                     return Integer.MIN_VALUE;
30                 }
31             }
32             if (sum == (long) Integer.MAX_VALUE + 1) {
33                 if (flag) {
34                     return Integer.MAX_VALUE;
35                 }
36             }
37             start++;
38         }
39         if (!flag) {
40             sum = -sum;
41         }
42         return (int) sum;
43     }
44 }
View Code

 

面试题53 -- 通配符匹配

Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).

Example
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false

思路:tricky

 1 public class Solution {
 2     /**
 3      * @param s: A string
 4      * @param p: A string includes "?" and "*"
 5      * @return: A boolean
 6      */
 7     public boolean isMatch(String s, String p) {
 8         // write your code here
 9         if (s == null || p == null) {
10             return false;
11         }
12         int indexS = 0;
13         int match = 0;
14         int indexP = 0;
15         int startIndex = -1;
16         while (indexS < s.length()) {
17             if (indexP < p.length() && (s.charAt(indexS) == p.charAt(indexP)
18                 || p.charAt(indexP) == '?')) {
19                 indexS++;
20                 indexP++;
21             }
22             else if (indexP < p.length() && p.charAt(indexP) == '*') {
23                 startIndex = indexP;
24                 indexP++;
25                 match = indexS;
26             }
27             else if (startIndex != -1) {
28                 indexP = startIndex + 1;
29                 match++;
30                 indexS = match;
31             }
32             else {
33                 return false;
34             }
35         }
36         while (indexP < p.length() && p.charAt(indexP) == '*') {
37             indexP++;
38         }
39         return indexP == p.length();
40      }
41 }
View Code

 

Fizz Buzz

Given number n. Print number from 1 to n. But:

when number is divided by 3, print "fizz".
when number is divided by 5, print "buzz".
when number is divided by both 3 and 5, print "fizz buzz".

If n = 15, you should return:

[
  "1", "2", "fizz",
  "4", "buzz", "fizz",
  "7", "8", "fizz",
  "buzz", "11", "fizz",
  "13", "14", "fizz buzz"
]
题目
public class Solution {
    /*
     * @param n: An integer
     * @return: A list of strings.
     */
    public List<String> fizzBuzz(int n) {
        // write your code here
        List<String> result = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            if (i % 15 == 0) {
                result.add("fizz buzz");
            } else if (i % 3 == 0) {
                result.add("fizz");
            } else if (i % 5 == 0) {
                result.add("buzz");
            } else {
                // 只能放String类型,需要加上""将int类型转成String类型
                result.add(i + "");
            }
        }
        return result;
    }
}    
View Code

 

面试题6 - 前序 + 中序 重建二叉树

给定二叉树的前序遍历数组和中序遍历数组,构建二叉树,不含重复的元素。比如前序遍历[1, 2, 4, 7, 3, 5, 6, 8]和中序遍历[4, 7, 2, 1, 5, 3, 8, 6],构建该二叉树。

思路:前序遍历第一个元素为根节点,然后根据该值在中序遍历中找到根节点的位置,这样左子树的前序遍历和遍历就找到了,右子树的前序遍历和中序遍历也找到了,然后递归下去即可。

 

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12  
13  
14 public class Solution {
15     /**
16      *@param preorder : A list of integers that preorder traversal of a tree
17      *@param inorder : A list of integers that inorder traversal of a tree
18      *@return : Root of a tree
19      */
20     public TreeNode buildTree(int[] preorder, int[] inorder) {
21         // write your code here
22         if (preorder == null || preorder.length == 0 || inorder == null
23             || inorder.length == 0 || preorder.length != inorder.length) {
24             return null;
25         }
26         return helper(preorder, 0, inorder, 0, inorder.length - 1);
27     }
28     public TreeNode helper(int[] preorder, int preStart,
29                            int[] inorder, int inStart, int inEnd) {
30         if (inStart > inEnd) {
31             return null;
32         }
33         TreeNode root = new TreeNode(preorder[preStart]);
34         int inRootIndex = 0;
35         for (int i = inStart; i <= inEnd; i++) {
36             if (preorder[preStart] == inorder[i]) {
37                 inRootIndex = i;
38             }
39         }
40         root.left = helper(preorder, preStart + 1, inorder, inStart, inRootIndex - 1);
41         root.right = helper(preorder, preStart + 1 + inRootIndex - inStart, inorder, inRootIndex + 1, inEnd);
42         return root;
43     }
44 }
View Code

 

Follow Up - 中序 + 后序 重建二叉树

思路同上

 1 public class Solution {
 2     /*
 3      * @param inorder: A list of integers that inorder traversal of a tree
 4      * @param postorder: A list of integers that postorder traversal of a tree
 5      * @return: Root of a tree
 6      */
 7     public TreeNode buildTree(int[] inorder, int[] postorder) {
 8         // write your code here
 9         if (inorder == null || inorder.length == 0 || postorder == null
10             || postorder.length == 0 || inorder.length != postorder.length) {
11             return null;
12         }
13         return helper(inorder, 0, inorder.length - 1,
14                       postorder, postorder.length - 1);
15     }
16     public TreeNode helper(int[] inorder, int inStart, int inEnd,
17                            int[] postorder, int postStart) {
18         if (inStart > inEnd) {
19             return null;
20         }               
21         TreeNode root = new TreeNode(postorder[postStart]);
22         int inRootIndex = 0;
23         for (int i = inStart; i <= inEnd; i++) {
24             if (inorder[i] == postorder[postStart]) {
25                 inRootIndex = i;
26             }
27         }
28         root.left = helper(inorder, inStart, inRootIndex - 1, postorder, postStart - 1 - (inEnd - inRootIndex));
29         root.right = helper(inorder, inRootIndex + 1, inEnd, postorder, postStart - 1);
30         return root;
31     }
32 }
View Code

 

Follow Up - 层序 + 中序 重建二叉树

需要注意左右子树的层序遍历集合融合在一起,需要分开

import java.util.*;

public class Main {

    private static List<Integer> preorder = new ArrayList<>();
    private static List<Integer> postorder = new ArrayList<>();

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        String[] s1 = in.nextLine().split(" ");
        List<Integer> layer = new ArrayList<>();
        for (String s : s1) {
            layer.add(Integer.parseInt(s));
        }
        String[] s2 = in.nextLine().split(" ");
        int[] inorder = new int[s2.length];
        for (int i = 0; i < inorder.length; i++) {
            inorder[i] = Integer.parseInt(s2[i]);
        }
        TreeNode root = constructFromLayerInOrder(layer, inorder, 0, inorder.length - 1);
        preorder(root);
        postorder(root);
        System.out.println(preorder);
        System.out.println(postorder);
    }

    public static TreeNode constructFromLayerInOrder(List<Integer> layer, int[] inorder, int inStart, int inEnd) {
        if (inStart > inEnd) {
            return null;
        }
        TreeNode root = new TreeNode(layer.get(0));
        int rootIndex = inStart;
        for (; rootIndex <= inEnd; rootIndex++) {
            if (inorder[rootIndex] == layer.get(0)) {
                break;
            }
        }
        List<Integer> leftLayer = new ArrayList<>();
        List<Integer> rightLayer = new ArrayList<>();
        for (int i = 1; i < layer.size(); i++) {
            boolean isLeft = false;
            for (int j = inStart; j < rootIndex; j++) {
                if (inorder[j] == layer.get(i)) {
                    isLeft = true;
                }
            }
            if (isLeft == true) {
                leftLayer.add(layer.get(i));
            } else {
                rightLayer.add(layer.get(i));
            }
        }
        root.left = constructFromLayerInOrder(leftLayer, inorder, inStart, rootIndex - 1);
        root.right = constructFromLayerInOrder(rightLayer, inorder, rootIndex + 1, inEnd);
        return root;
    }

    public static void preorder(TreeNode root) {
        if (root == null) {
            return;
        }
        preorder.add(root.val);
        preorder(root.left);
        preorder(root.right);
    }

    public static void postorder(TreeNode root) {
        if (root == null) {
            return;
        }
        postorder(root.left);
        postorder(root.right);
        postorder.add(root.val);
    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}
View Code

 

二叉树前序遍历

递归

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A Tree
17      * @return: Preorder in ArrayList which contains node values.
18      */
19     public List<Integer> preorderTraversal(TreeNode root) {
20         // write your code here
21         List<Integer> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         dfsHelper(result, root);
26         return result;
27     }
28     public void dfsHelper(List<Integer> result, TreeNode root) {
29         if (root == null) {
30             return;
31         }
32         result.add(root.val);
33         dfsHelper(result, root.left);
34         dfsHelper(result, root.right);
35     }
36 }
View Code

 非递归

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A Tree
17      * @return: Preorder in ArrayList which contains node values.
18      */
19     public List<Integer> preorderTraversal(TreeNode root) {
20         // write your code here
21         List<Integer> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         Stack<TreeNode> stack = new Stack<>();
26         stack.push(root);
27         while (!stack.isEmpty()) {
28             TreeNode node = stack.pop();
29             result.add(node.val);
30             if (node.right != null) {
31                 stack.push(node.right);
32             }
33             if (node.left != null) {
34                 stack.push(node.left);
35             }
36         }
37         return result;
38     }
39 }
View Code

分治

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A Tree
17      * @return: Preorder in ArrayList which contains node values.
18      */
19     public List<Integer> preorderTraversal(TreeNode root) {
20         // write your code here
21         List<Integer> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         List<Integer> leftResult = preorderTraversal(root.left);
26         List<Integer> rightResult = preorderTraversal(root.right);
27         result.add(root.val);
28         result.addAll(leftResult);
29         result.addAll(rightResult);
30         return result;
31     }
32 }
View Code

 

二叉树中序遍历

递归

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A Tree
17      * @return: Inorder in ArrayList which contains node values.
18      */
19     public List<Integer> inorderTraversal(TreeNode root) {
20         // write your code here
21         List<Integer> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         dfsHelper(result, root);
26         return result;
27     }
28     public void dfsHelper(List<Integer> result, TreeNode root) {
29         if (root == null) {
30             return;
31         }
32         dfsHelper(result, root.left);
33         result.add(root.val);
34         dfsHelper(result, root.right);
35     }
36 }
View Code

 

非递归

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A Tree
17      * @return: Inorder in ArrayList which contains node values.
18      */
19     public List<Integer> inorderTraversal(TreeNode root) {
20         // write your code here
21         List<Integer> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         Stack<TreeNode> stack = new Stack<>();
26         TreeNode cur = root;
27         while (cur != null || !stack.isEmpty()) {
28             while (cur != null) {
29                 stack.push(cur);
30                 cur = cur.left;
31             }
32             cur = stack.pop();
33             result.add(cur.val);
34             cur = cur.right;
35         }
36         return result;
37     }
38 }
View Code

 

分治

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A Tree
17      * @return: Inorder in ArrayList which contains node values.
18      */
19     public List<Integer> inorderTraversal(TreeNode root) {
20         // write your code here
21         List<Integer> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         List<Integer> leftResult = inorderTraversal(root.left);
26         List<Integer> rightResult = inorderTraversal(root.right);
27         result.addAll(leftResult);
28         result.add(root.val);
29         result.addAll(rightResult);
30         return result;
31     }
32 }
View Code

  

二叉树后序遍历

递归

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A Tree
17      * @return: Postorder in ArrayList which contains node values.
18      */
19     public List<Integer> postorderTraversal(TreeNode root) {
20         // write your code here
21         List<Integer> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         dfsHelper(result, root);
26         return result;
27     }
28     public void dfsHelper(List<Integer> result, TreeNode root) {
29         if (root == null) {
30             return;
31         }
32         dfsHelper(result, root.left);
33         dfsHelper(result, root.right);
34         result.add(root.val);
35     }
36 }
View Code

 

非递归

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A Tree
17      * @return: Postorder in ArrayList which contains node values.
18      */
19     public List<Integer> postorderTraversal(TreeNode root) {
20         // write your code here
21         List<Integer> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         Stack<TreeNode> stack = new Stack<>();
26         stack.push(root);
27         TreeNode pre = null, cur = root;
28         while (!stack.isEmpty()) {
29             cur = stack.peek();
30             if (pre == null || pre.left == cur || pre.right == cur) {
31                 if (cur.left != null) {
32                     stack.push(cur.left);
33                 } else if (cur.right != null) {
34                     stack.push(cur.right);
35                 }
36             } else if (cur.left == pre) {
37                 if (cur.right != null) {
38                     stack.push(cur.right);
39                 }
40             } else {
41                 stack.pop();
42                 result.add(cur.val);
43             }
44             pre = cur;
45         }
46         return result;
47     }
48 }
View Code

 

分治

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A Tree
17      * @return: Postorder in ArrayList which contains node values.
18      */
19     public List<Integer> postorderTraversal(TreeNode root) {
20         // write your code here
21         List<Integer> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         List<Integer> leftResult = postorderTraversal(root.left);
26         List<Integer> rightResult = postorderTraversal(root.right);
27         result.addAll(leftResult);
28         result.addAll(rightResult);
29         result.add(root.val);
30         return result;
31     }
32 }
View Code

 

层序遍历 -- 从上到下(BFS) 

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A Tree
17      * @return: Level order a list of lists of integer
18      */
19     public List<List<Integer>> levelOrder(TreeNode root) {
20         // write your code here
21         List<List<Integer>> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         Queue<TreeNode> queue = new LinkedList<>();
26         queue.offer(root);
27         while (!queue.isEmpty()) {
28             List<Integer> tempList = new ArrayList<>();
29             int size = queue.size();
30             for (int i = 0; i < size; i++) {
31                 TreeNode node = queue.poll();
32                 tempList.add(node.val);
33                 if (node.left != null) {
34                     queue.offer(node.left);
35                 }
36                 if (node.right != null) {
37                     queue.offer(node.right);
38                 }
39             }
40             result.add(tempList);
41         }
42         return result;
43     }
44 }
View Code

 

 层序遍历 -- 从下到上(BFS)

思路同上,只是调用的是List的add(int index, E element)方法result.add(0, tempList)

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A tree
17      * @return: buttom-up level order a list of lists of integer
18      */
19     public List<List<Integer>> levelOrderBottom(TreeNode root) {
20         // write your code here
21         List<List<Integer>> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         Queue<TreeNode> queue = new LinkedList<>();
26         queue.offer(root);
27         while (!queue.isEmpty()) {
28             List<Integer> tempList = new ArrayList<>();
29             int size = queue.size();
30             for (int i = 0; i < size; i++) {
31                 TreeNode node = queue.poll();
32                 tempList.add(node.val);
33                 if (node.left != null) {
34                     queue.offer(node.left);
35                 }
36                 if (node.right != null) {
37                     queue.offer(node.right);
38                 }
39             }
40             result.add(0, tempList);
41         }
42         return result;
43     }
44 }
View Code

 

之字型遍历 -- 先从左往右,再从右往左,以此类推。

思路同上,要定义一个标记为startLeft标识是否要从左往右打印,如果是,调用tempList.add(node.val),如果不是,调用tempList.add(0, node.val)

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: A Tree
17      * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
18      */
19     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
20         // write your code here
21         List<List<Integer>> result = new ArrayList<>();
22         if (root == null) {
23             return result;
24         }
25         Queue<TreeNode> queue = new LinkedList<>();
26         queue.offer(root);
27         boolean startLeft = true;
28         while (!queue.isEmpty()) {
29             List<Integer> tempList = new ArrayList<>();
30             int size = queue.size();
31             for (int i = 0; i < size; i++) {
32                 TreeNode node = queue.poll();
33                 if (startLeft) {
34                     tempList.add(node.val);
35                 } else {
36                     tempList.add(0, node.val);
37                 }
38                 if (node.left != null) {
39                     queue.offer(node.left);
40                 }
41                 if (node.right != null) {
42                     queue.offer(node.right);
43                 }
44             }
45             result.add(tempList);
46             startLeft = !startLeft;
47         }
48         return result;
49     }
50 }
View Code

 

 

Binary Tree Path Sum -- 二叉树中和为某一值的从根节点到叶节点的路径

注意:前序遍历,每访问到一个节点时,添加进路径中,并累加当前和。如果该节点为叶节点,则判断当前和是否等于给定值,如果等于则将路径加入到结果集中。记得每次递归返回上一层时把当前节点从路径中删除。

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: the root of binary tree
17      * @param target: An integer
18      * @return: all valid paths
19      */
20     public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
21         // write your code here
22         List<List<Integer>> result = new ArrayList<>();
23         if (root == null) {
24             return result;
25         }
26         dfsHelper(result, new ArrayList<Integer>(), root, target);
27         return result;
28     }
29     public void dfsHelper(List<List<Integer>> result, List<Integer> tempList,                        TreeNode root, int target) {
30         tempList.add(root.val);
31         if (root.left == null && root.right == null) {
32             if (target == root.val) {
33                 result.add(new ArrayList<Integer>(tempList));
34             }
35             tempList.remove(tempList.size() - 1);
36             return;
37         }
38         if (root.left != null) {
39             dfsHelper(result, tempList, root.left, target - root.val);
40         }
41         if (root.right != null) {
42             dfsHelper(result, tempList, root.right, target - root.val);
43         }
44         tempList.remove(tempList.size() - 1);
45     }
46 }
View Code

 

 

Clone Binary Tree -- 复制二叉树

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: The root of binary tree
17      * @return: root of new tree
18      */
19     public TreeNode cloneTree(TreeNode root) {
20         // write your code here
21         if (root == null) {
22             return null;
23         }
24         TreeNode newRoot = new TreeNode(root.val);
25         newRoot.left = cloneTree(root.left);
26         newRoot.right = cloneTree(root.right);
27         return newRoot;
28     }
29 }
View Code

 

Clone Mirror Binary Tree -- 二叉树镜像

对于每个非叶节点,交换其左右子节点,递归下去。

 1 public class Solution {
 2     public void mirrorBinaryTree(TreeNode root) {
 3         if (root == null) {
 4             return;
 5         }
 6         if (root.left == null && root.right == null) {
 7             return;
 8         }
 9         TreeNode tempNode = root.left;
10         root.left = root.right;
11         root.right = tempNode;
12         if (root.left != null) {
13             mirrorBinaryTree(root.left);
14         }
15         if (root.right != null) {
16             mirrorBinaryTree(root.right);
17         }
18     }
19 }
View Code

 

String Permutation -- 判断一个串是否是另一个串的全排列

思路:建一个长度为256的int型数组,在字符串A中增加次数,在字符串B中减去次数,最后遍历一遍数组,如果全部元素为0才能说明A是B的全排列,否则不是。

 1 public class Solution {
 2     /*
 3      * @param A: a string
 4      * @param B: a string
 5      * @return: a boolean
 6      */
 7     public boolean Permutation(String A, String B) {
 8         // write your code here
 9         int[] count = new int[256];
10         for (int i = 0; i < A.length(); i++) {
11             count[A.charAt(i)]++;
12         }
13         for (int i = 0; i < B.length(); i++) {
14             count[B.charAt(i)]--;
15         }
16         for (int i = 0; i < 256; i++) {
17             if (count[i] != 0) {
18                 return false;
19             }
20         }
21         return true;
22     }
23 }
View Code

 

String Permutation II -- 求一个字符串的所有全排列字符串

 

 

Min Stack

思路:一个栈存值,另一个栈存当先栈中的最小值。

 1 public class MinStack {
 2     
 3     Stack<Integer> stack;
 4     Stack<Integer> minStack;
 5     
 6     public MinStack() {
 7         // do intialization if necessary
 8         stack = new Stack<Integer>();
 9         minStack = new Stack<Integer>();
10     }
11 
12     /*
13      * @param number: An integer
14      * @return: nothing
15      */
16     public void push(int number) {
17         // write your code here
18         stack.push(number);
19         if (minStack.isEmpty()) {
20             minStack.push(number);
21         } else {
22             minStack.push(Math.min(number, minStack.peek()));
23         }
24     }
25 
26     /*
27      * @return: An integer
28      */
29     public int pop() {
30         // write your code here
31         minStack.pop();
32         return stack.pop();
33     }
34 
35     /*
36      * @return: An integer
37      */
38     public int min() {
39         // write your code here
40         if (minStack.isEmpty()) {
41             return -1;
42         }
43         return minStack.peek();
44     }
45 }
View Code

 

二叉搜索树转双向链表

Convert a binary search tree to doubly linked list with in-order traversal.

Example
Given a binary search tree:

    4
   / \
  2   5
 / \
1   3
return 1<->2<->3<->4<->5
View Code

思路:建立一个辅助函数helper,其函数返回类型为ResultType,ResultType记录当前节点为根节点的树中的最左边的双向链表节点和最右边的双向链表节点。

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  * Definition for Doubly-ListNode.
12  * public class DoublyListNode {
13  *     int val;
14  *     DoublyListNode next, prev;
15  *     DoublyListNode(int val) {
16  *         this.val = val;
17  *         this.next = this.prev = null;
18  *     }
19  * }
20  */
21 
22 class ResultType {
23     DoublyListNode first;
24     DoublyListNode last;
25     public ResultType(DoublyListNode first, DoublyListNode last) {
26         this.first = first;
27         this.last = last;
28     }
29 }
30 
31 public class Solution {
32     /*
33      * @param root: The root of tree
34      * @return: the head of doubly list node
35      */
36     public DoublyListNode bstToDoublyList(TreeNode root) {
37         // write your code here
38         if (root == null) {
39             return null;
40         }
41         ResultType result = helper(root);
42         return result.first;
43     }
44     public ResultType helper(TreeNode root) {
45         if (root == null) {
46             return null; 
47         }
48         ResultType result = new ResultType(null, null);
49         DoublyListNode node = new DoublyListNode(root.val);
50         ResultType left = helper(root.left);
51         ResultType right = helper(root.right);
52         if (left == null) {
53             result.first = node;
54         } else {
55             result.first = left.first;
56             node.prev = left.last;
57             left.last.next = node;
58         }
59         if (right == null) {
60             result.last = node;
61         } else {
62             result.last = right.last;
63             node.next = right.first;
64             right.first.prev = node;
65         }
66         return result;
67     }
68 }
View Code

 

Maximum Subarray -- 连续子数组的最大和

思路:sum当前和  minSum到当前位置的和最小的子数组(index从0开始)  max当前位置为止连续子数组的最大和

 1 public class Solution {
 2     /*
 3      * @param nums: A list of integers
 4      * @return: A integer indicate the sum of max subarray
 5      */
 6     public int maxSubArray(int[] nums) {
 7         // write your code here
 8         if (nums == null || nums.length == 0) {
 9             return 0;
10         }
11         int sum = 0, minSum = 0;
12         int max = Integer.MIN_VALUE;
13         for (int i = 0; i < nums.length; i++) {
14             sum += nums[i];
15             if (sum - minSum > max) {
16                 max = sum - minSum;
17             }
18             minSum = Math.min(minSum, sum);
19         }
20         return max;
21     }
22 }
View Code

 

Maximum Subarray II

找两个不重叠的子数组使得两个子数组的和加起来最大

思路:从前往后做一遍Maximum Subarray,用一个数组left记录到当前位置为止子数组的最大和;从后往前做一遍Maximum Subarray,用一个数组right记录到当前位置为止子数组的最大和;然后两个子数组的和等价于left[i] + right[i + 1],遍历i求得该最大值。

 1 public class Solution {
 2     /*
 3      * @param nums: A list of integers
 4      * @return: An integer denotes the sum of max two non-overlapping subarrays
 5      */
 6     public int maxTwoSubArrays(List<Integer> nums) {
 7         // write your code here
 8         if (nums == null || nums.size() <= 1) {
 9             return 0;
10         }
11         int sum = 0, minSum = 0;
12         int max = Integer.MIN_VALUE;
13         int[] left = new int[nums.size()];
14         for (int i = 0; i < nums.size(); i++) {
15             sum += nums.get(i);
16             if (sum - minSum > max) {
17                 max = sum - minSum;
18             }
19             minSum = Math.min(minSum, sum);
20             left[i] = max;
21         }
22         sum = 0;
23         minSum = 0;
24         max = Integer.MIN_VALUE;
25         int[] right = new int[nums.size()];
26         for (int i = nums.size() - 1; i >= 0; i--) {
27             sum += nums.get(i);
28             if (sum - minSum > max) {
29                 max = sum - minSum;
30             }
31             minSum = Math.min(minSum, sum);
32             right[i] = max;
33         }
34         max = Integer.MIN_VALUE;
35         for (int i = 0; i < nums.size() - 1; i++) {
36             if (left[i] + right[i + 1] > max) {
37                 max = left[i] + right[i + 1];
38             }
39         }
40         return max;
41     }
42 }
View Code

 

Maximum Subarray III 

思路:

local[i][k]表示前i个元素取k个子数组并且必须包含第i个元素的最大和。

global[i][k]表示前i个元素取k个子数组不一定包含第i个元素的最大和。

local[i][k]的状态函数:

max(global[i-1][k-1], local[i-1][k]) + nums[i-1]

有两种情况,第一种是第i个元素自己组成一个子数组,则要在前i-1个元素中找k-1个子数组,第二种情况是第i个元素属于前一个元素的子数组,因此要在i-1个元素中找k个子数组(并且必须包含第i-1个元素,这样第i个元素才能合并到最后一个子数组中),取两种情况里面大的那个。

global[i][k]的状态函数:

max(global[i-1][k],local[i][k])

有两种情况,第一种是不包含第i个元素,所以要在前i-1个元素中找k个子数组,第二种情况为包含第i个元素,在i个元素中找k个子数组且必须包含第i个元素,取两种情况里面大的那个。

注意这一题中DP的方向是先从上往下,再从左往右,而不是通常的先从左往右,再从上往下。这样做是因为localMax[j - 1][j]和globalMax[j - 1][j]置为Integer.MIN_VALUE的次数取决于列循环次数,而不是取决于行循环次数,否则二维数组下标会越界。

 1 public class Solution {
 2     /*
 3      * @param nums: A list of integers
 4      * @param k: An integer denote to find k non-overlapping subarrays
 5      * @return: An integer denote the sum of max k non-overlapping subarrays
 6      */
 7     public int maxSubArray(int[] nums, int k) {
 8         // write your code here
 9         if (nums == null || nums.length == 0 || k <= 0 || k > nums.length) {
10             return 0;
11         }
12         int[][] localMax = new int[nums.length + 1][k + 1];
13         int[][] globalMax = new int[nums.length + 1][k + 1];
14         for (int j = 1; j <= k; j++) {
15             localMax[j - 1][j] = Integer.MIN_VALUE;
16             globalMax[j - 1][j] = Integer.MIN_VALUE;
17             for (int i = j; i <= nums.length; i++) {
18                 localMax[i][j] = Math.max(globalMax[i - 1][j - 1], localMax[i - 1][j]) + nums[i - 1];
19                 globalMax[i][j] = Math.max(globalMax[i - 1][j], localMax[i][j]);
20             }
21         }
22         return globalMax[nums.length][k];
23     }
24 }
View Code

 

Reverse Pairs -- 求数组中逆序对的个数

思路:归并排序中统计逆序对的个数,统计的时候顺便把temp也赋值了,此时mergeSort函数要有返回值,表示当前数组的逆序对个数。

 1 public class Solution {
 2     /*
 3      * @param A: an array
 4      * @return: total of reverse pairs
 5      */
 6     public long reversePairs(int[] A) {
 7         // write your code here
 8         if (A == null || A.length == 0) {
 9             return 0;
10         }
11         return mergeSort(A, new int[A.length], 0, A.length - 1);
12     }
13     public int mergeSort(int[] A, int[] temp, int start, int end) {
14         if (start == end) {
15             return 0;
16         }
17         int count = 0;
18         int mid = start + (end - start) / 2;
19         int leftCount = mergeSort(A, temp, start, mid);
20         int rightCount = mergeSort(A, temp, mid + 1, end);
21         int left = mid, right = end;
22         int index = end;
23         while (left >= start && right >= mid + 1) {
24             if (A[left] > A[right]) {
25                 count += right - mid;
26                 temp[index--] = A[left];
27                 left--;
28             } else {
29                 temp[index--] = A[right];
30                 right--;
31             }
32         }
33         while (left >= start) {
34             temp[index--] = A[left--];
35         }
36         while (right >= mid + 1) {
37             temp[index--] = A[right--];
38         }
39         for (int i = start; i <= end; i++) {
40             A[i] = temp[i];
41         }
42         return count + leftCount + rightCount;
43     }
44 }
View Code

 

Reorder array to construct the minimum number -- 把数组排成最小的数

思路:由于组合之后的数很大,这是一个大数问题,所以用字符串来处理。先把整型数组转成字符串数组,再定义比较器来排序:Arrays.sort(temp, cmp),关键是比较器的比较规则的定义。最后注意前导0的处理,挑选出第一个不为'0'的位置,然后截取字符串返回即可,这里可能字符串全是0,这种情况特殊处理,返回"0"

 

 Kth Largest Element -- 找第K大元素

思路I:小根堆

 1 class Solution {
 2     /*
 3      * @param k : description of k
 4      * @param nums : array of nums
 5      * @return: description of return
 6      */
 7     public int kthLargestElement(int k, int[] nums) {
 8         // write your code here
 9         if (nums == null || nums.length == 0 || k < 1 || k > nums.length) {
10             return 0;
11         }
12         PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k);
13         for (int i = 0; i < nums.length; i++) {
14             if (pq.size() < k) {
15                 pq.offer(nums[i]);
16             } else {
17                 if (nums[i] > pq.peek()) {
18                     pq.poll();
19                     pq.offer(nums[i]);
20                 }
21             }
22         }
23         return pq.peek();
24     }
25 };
View Code

思路II:快排。从大到小排序,选第K大的数。

 1 class Solution {
 2     /*
 3      * @param k : description of k
 4      * @param nums : array of nums
 5      * @return: description of return
 6      */
 7     public int kthLargestElement(int k, int[] nums) {
 8         // write your code here
 9         if (nums == null || nums.length == 0 || k < 1 || k > nums.length) {
10             return 0;
11         }
12         return quickSort(nums, 0, nums.length - 1, k);
13     }
14     public int quickSort(int[] nums, int start, int end, int k) {
15         if (start == end) {
16             return nums[start];
17         }
18         int mid = start + (end - start) / 2;
19         int pivot = nums[mid];
20         int left = start, right = end;
21         while (left <= right) {
22             while (left <= right && nums[left] > pivot) {
23                 left++;
24             }
25             while (left <= right && nums[right] < pivot) {
26                 right--;
27             }
28             if (left <= right) {
29                 int temp = nums[left];
30                 nums[left] = nums[right];
31                 nums[right] = temp;
32                 left++;
33                 right--;
34             }
35         }
36         if (k <= right - start + 1) {
37             return quickSort(nums, start, right, k);
38         }
39         if (k >= left - start + 1) {
40             return quickSort(nums, left, end, k - (left - start));
41         }
42         return nums[right + 1];
43     }
44 };
View Code

 

 Single Number -- 数组中一个数出现1次,其余数出现2次

思路:异或,最后得出的数即为所求。a ^ a = 0  0 ^ a = a

 1 public class Solution {
 2     /*
 3      * @param A: An integer array
 4      * @return: An integer
 5      */
 6     public int singleNumber(int[] A) {
 7         // write your code here
 8         if (A == null || A.length % 2 == 0) {
 9             return 0;
10         }
11         int result = 0;
12         for (int i = 0; i < A.length; i++) {
13             result ^= A[i];
14         }
15         return result;
16     }
17 }
View Code

 

Single Number II -- 数组中一个数出现1次,其余数出现3次

思路:对于数组中所有数,某一位中bit 1的个数为 3 * n + 1,说明这个bit位上落单的1就是那个在数组中只出现1次的数的,循环32次找出所有落单的数的bit 1

 1 public class Solution {
 2     /*
 3      * @param A: An integer array
 4      * @return: An integer
 5      */
 6     public int singleNumberII(int[] A) {
 7         // write your code here
 8         if (A == null || A.length % 3 != 1) {
 9             return 0;
10         }
11         int result = 0;
12         for (int i = 0; i < 32; i++) {
13             int count = 0;
14             for (int j = 0; j < A.length; j++) {
15                 if ((A[j] & (1 << i)) != 0) {
16                     count++;
17                 }
18             }
19             result |= (count % 3) << i;
20         }
21         return result;
22     }
23 }
View Code

 

Single Number III -- 数组中有2个数出现一次,其余数出现2次

 思路:将只出现1次的两个数分开,再利用Single Number的解法即可。关键是符合分开这两个数:方法是先将数组中所有元素进行一遍异或运算,得到的结果是这两个数异或的结果,然后取这个结果的最右边开始的为bit 1的位置。在这个位置上,一个数在该位置上为bit 1,另一个数在该位置上为bit 0,这样通过判断数组中一个数在该位置上的bit位是否为1就可以分开这两个数,至于其余出现两次的数,这些数字成对的落在哪个出现一次的数的区域都可以,不影响结果。

 1 public class Solution {
 2     /*
 3      * @param A: An integer array
 4      * @return: An integer array
 5      */
 6     public List<Integer> singleNumberIII(int[] A) {
 7         // write your code here
 8         List<Integer> result = new ArrayList<>();
 9         if (A == null || A.length == 0 || A.length % 2 != 0) {
10             return result;
11         }
12         int num = 0;
13         for (int i = 0; i < A.length; i++) {
14             num ^= A[i];
15         }
16         int index = 0;
17         for (int i = 0; i < 32; i++) {
18             if ((num & (1 << i)) != 0) {
19                 index = i;
20                 break;
21             }
22         }
23         int num1 = 0, num2 = 0;
24         for (int i = 0; i < A.length; i++) {
25             if ((A[i] & (1 << index)) != 0) {
26                 num1 ^= A[i];
27             } else {
28                 num2 ^= A[i];
29             }
30         }
31         result.add(num1);
32         result.add(num2);
33         return result;
34     }
35 }
View Code

 

Two Sum -- 数组中找两个数的和为给定值target,返回这两个数的索引

思路:注意题目要求的是返回这两个数的索引,而不是返回这两个数。所以常规的做法(先对数组排序,然后前后指针来求得这两个数,其和等于target)行不通,就算用Map来在排序前存储好每个数和其索引的映射也不行,因为有可能是 3 + 3 = 6这种情况,此时Map不能同时存储两个3的索引。

所以只能用另一种方法:遍历数组的每个元素,每次都用Map存储  target - 当前元素值 --> 当前元素索引的映射关系,如果当前map含有target - 当前元素值,说明找到了,返回这两个索引。

 1 public class Solution {
 2     /*
 3      * @param numbers: An array of Integer
 4      * @param target: target = numbers[index1] + numbers[index2]
 5      * @return: [index1 + 1, index2 + 1] (index1 < index2)
 6      */
 7     public int[] twoSum(int[] numbers, int target) {
 8         // write your code here
 9         if (numbers == null || numbers.length < 2) {
10             return new int[0];
11         }
12         Map<Integer, Integer> map = new HashMap<>();
13         for (int i = 0; i < numbers.length; i++) {
14             if (map.containsKey(numbers[i])) {
15                 return new int[] {map.get(numbers[i]), i};
16             }
17             map.put(target - numbers[i], i);
18         }
19         return new int[0];
20     }
21 }
View Code

 

A + B Problem -- 不用加减乘除做加法

思路:既然不能用四则运算,那么只能用位运算了。加法分为两步:1. 不进位做加法 -- 类似于二进制中的异或运算 0 ^ 0 = 0, 0 ^ 1 = 0, 1 ^ 0 = 0, 1 & 1 = 1  2. 进位与不进位做加法的结果相加 -- 类似于二进制的先位与运算 0 & 0 = 0,0 & 1 = 0,1 & 0 = 0,1 & 1 = 1,再左移一位。

 1 public class Solution {
 2     /**
 3      * @param a: An integer
 4      * @param b: An integer
 5      * @return: The sum of a and b
 6      */
 7     public int aplusb(int a, int b) {
 8         // write your code here
 9         int sum = a ^ b;
10         int carry = (a & b) << 1;
11         while (carry != 0) {
12             a = sum;
13             b = carry;
14             sum = a ^ b;
15             carry = (a & b) << 1;
16         }
17         return sum;
18     }
19 }
View Code

 

Maximum Depth of Binary Tree -- 二叉树最大深度

思路I: 分治法Divide Conquer

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param root: The root of binary tree.
15      * @return: An integer.
16      */
17     public int maxDepth(TreeNode root) {
18         // write your code here
19         if (root == null) {
20             return 0;
21         }
22         int left = maxDepth(root.left);
23         int right = maxDepth(root.right);
24         return 1 + Math.max(left, right);
25     }
26 }
View Code

思路II:遍历法Traverse

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param root: The root of binary tree.
15      * @return: An integer.
16      */
17     private int depth = 0;
18     public int maxDepth(TreeNode root) {
19         // write your code here
20         if (root == null) {
21             return 0;
22         }
23         helper(root, 1);
24         return depth;
25     }
26     public void helper(TreeNode root, int curDepth) {
27         if (root == null) {
28             return;
29         }
30         if (curDepth > depth) {
31             depth = curDepth;
32         }
33         helper(root.left, curDepth + 1);
34         helper(root.right, curDepth + 1);
35     }
36 }
View Code

 

 Reverse Words in a String -- 翻转单词顺序

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Have you met this question in a real interview? Yes
Clarification
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
题目

思路I:调用String的split(" ")的方法 + StringBuilder从split的数组后往前加入单词和" ",如果split的数组中有""说明这里有大于1个的空格字符,这种情况就不要加入到StringBuilder中了。

 1 public class Solution {
 2     /*
 3      * @param s: A string
 4      * @return: A string
 5      */
 6     public String reverseWords(String s) {
 7         // write your code here
 8         if (s ==  null || s.length() == 0) {
 9             return "";
10         }
11         String[] str = s.split(" ");
12         StringBuilder sb = new StringBuilder();
13         for (int i = str.length - 1; i >= 0; i--) {
14             if (str[i] == "") {
15                 continue;
16             }
17             sb.append(str[i]).append(" ");
18         }
19         if (sb.length() == 0) {
20             return "";
21         }
22         return sb.substring(0, sb.length() - 1);
23     }
24 }
View Code

 

 变种:要求保留原有的所有空格

思路:两步翻转法:1 翻转整个字符串  2 翻转每个单词,采用前后指针实现,这里的注意事项标注在了代码中。

 1 public class Solution {
 2     public String ReverseSentence(String str) {
 3         if (str == null || str.length() <= 1) {
 4             return str;
 5         }
 6         char[] c = str.toCharArray();
 7         reverse(c, 0, c.length - 1);
 8         System.out.println(new String(c));
 9         int start = 0, end = 0;
10         while (start < c.length) {
11             if (c[start] == ' ') {
12                 start++;
13                 end++;
14             } else if (end == c.length || c[end] == ' ') { // 这里的else if的判断一定要注意顺序不能颠倒,否则会发生索引越界的异常。
15                 end--;
16                 reverse(c, start, end);
17                 start = end + 1;
18                 end = start;
19             } else {
20                 end++;
21             }
22         }
23         return new String(c);
24     }
25     public void reverse(char[] c, int start, int end) {
26         int left = start, right = end;
27         while (left < right) {
28             char temp = c[left];
29             c[left] = c[right];
30             c[right] = temp;
31             left++;
32             right--;
33         }
34     }
35 }
View Code

 

Rotate String

Given a string and an offset, rotate string by offset. (rotate from left to right)

Example
Given "abcdefg".

offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"
题目

思路:三步翻转法

 1 public class Solution {
 2     /*
 3      * @param str: An array of char
 4      * @param offset: An integer
 5      * @return: nothing
 6      */
 7     public void rotateString(char[] str, int offset) {
 8         // write your code here
 9         if (str == null || str.length <= 1
10             || offset < 0 || offset % str.length == 0) {
11             return;
12         }
13         offset = offset % str.length;
14         reverse(str, 0, str.length - 1);
15         reverse(str, 0, offset - 1);
16         reverse(str, offset, str.length - 1);
17     }
18     public void reverse(char[] str, int start, int end) {
19         int left = start, right = end;
20         while (left < right) {
21             char temp = str[left];
22             str[left] = str[right];
23             str[right] = temp;
24             left++;
25             right--;
26         }
27     }
28 }
View Code

 

Search for a Range -- 排序数组中找给定值的开始位置和结束位置

思路:二次二分,第一次二分找给定值在排序数组中第一次出现的位置,第二次二分找给定值在排序数组中最后一次出现的位置。

 1 public class Solution {
 2     /*
 3      * @param A: an integer sorted array
 4      * @param target: an integer to be inserted
 5      * @return: a list of length 2, [index1, index2]
 6      */
 7     public int[] searchRange(int[] A, int target) {
 8         // write your code here
 9         if (A == null || A.length == 0) {
10             return new int[] {-1, -1};
11         }
12         int start = 0, end = A.length - 1;
13         while (start + 1 < end) {
14             int mid = start + (end - start) / 2;
15             if (A[mid] == target) {
16                 end = mid;
17             } else if (A[mid] < target) {
18                 start = mid;
19             } else {
20                 end = mid;
21             }
22         }
23         int[] result = new int[2];
24         if (A[start] == target) {
25             result[0] = start;
26         } else if (A[end] == target) {
27             result[0] = end;
28         } else {
29             return new int[] {-1, -1};
30         }
31         start = 0;
32         end = A.length - 1;
33         while (start + 1 < end) {
34             int mid = start + (end - start) / 2;
35             if (A[mid] == target) {
36                 start = mid;
37             } else if (A[mid] < target) {
38                 start = mid;
39             } else {
40                 end = mid;
41             }
42         }
43         if (A[end] == target) {
44             result[1] = end;
45         } else if (A[start] == target) {
46             result[1] = start;
47         } 
48         // else {
49         //     return new int[] {-1, -1};
50         // }
51         return result;
52     }
53 }
View Code

 

Product of Array Exclude Itself

Given an integers array A.

Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], calculate B WITHOUT divide operation.

Have you met this question in a real interview? Yes
Example
For A = [1, 2, 3], return [6, 3, 2].
题目

思路:某一个位置的乘积值是有该位置左边所有元素的乘积和右边所有元素的乘积的乘积,所以可以建立一个left数组和right数组,left[i]表示前i个元素的乘积之和,right[i]表示后i个元素的乘积之和。

 1 public class Solution {
 2     /*
 3      * @param nums: Given an integers array A
 4      * @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
 5      */
 6     public List<Long> productExcludeItself(List<Integer> nums) {
 7         // write your code here
 8         List<Long> result = new ArrayList<>();
 9         if (nums == null || nums.size() == 0) {
10             return result;
11         }
12         long[] left = new long[nums.size() + 1];
13         left[0] = 1;
14         long[] right = new long[nums.size() + 1];
15         right[0] = 1;
16         for (int i = 1; i <= nums.size(); i++) {
17             left[i] = left[i - 1] * nums.get(i - 1);
18             right[i] = right[i - 1] * nums.get(nums.size() - i);
19         }
20         for (int i = 0; i < nums.size(); i++) {
21             result.add(left[i] * right[nums.size() - i - 1]);
22         }
23         return result;
24     }
25 }
View Code

 

序列化和反序列化二叉树

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.

 Notice

There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output of serialize as the input of deserialize, it won't check the result of serialize.

Have you met this question in a real interview? Yes
Example
An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure:

  3
 / \
9  20
  /  \
 15   7
Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.

You can use other method to do serializaiton and deserialization.
题目

思路:bfs。反序列化的时候,要设置一个标记为isLeftChild来判断当前节点是否为根节点的左儿子,以及建一个list用来存放非空节点,用index标注当前根节点。

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /**
16      * This method will be invoked first, you should design your own algorithm 
17      * to serialize a binary tree which denote by a root node to a string which
18      * can be easily deserialized by your own "deserialize" method later.
19      */
20     public String serialize(TreeNode root) {
21         // write your code here
22         if (root == null) {
23             return "{}";
24         }
25         Queue<TreeNode> queue = new LinkedList<>();
26         queue.offer(root);
27         StringBuilder sb = new StringBuilder();
28         sb.append("{").append(root.val).append(",");
29         while (!queue.isEmpty()) {
30             TreeNode node = queue.poll();
31             if (node.left != null) {
32                 queue.offer(node.left);
33                 sb.append(node.left.val).append(",");
34             } else {
35                 sb.append("#").append(",");
36             }
37             if (node.right != null) {
38                 queue.offer(node.right);
39                 sb.append(node.right.val).append(",");
40             } else {
41                 sb.append("#").append(",");
42             }
43         }
44         while (sb.charAt(sb.length() - 1) == ',' || sb.charAt(sb.length() - 1) == '#') {
45             sb.deleteCharAt(sb.length() - 1);
46         }
47         sb.append("}");
48         return sb.toString();
49     }
50 
51     /**
52      * This method will be invoked second, the argument data is what exactly
53      * you serialized at method "serialize", that means the data is not given by
54      * system, it's given by your own serialize method. So the format of data is
55      * designed by yourself, and deserialize it here as you serialize it in 
56      * "serialize" method.
57      */
58     public TreeNode deserialize(String data) {
59         // write your code here
60         if (data.equals("{}")) {
61             return null;
62         }
63         String[] str = data.substring(1, data.length() - 1).split(",");
64         boolean isLeftChild = true;
65         List<TreeNode> list = new ArrayList<>();
66         list.add(new TreeNode(Integer.parseInt(str[0])));
67         int index = 0;
68         for (int i = 1; i < str.length; i++) {
69             if (!str[i].equals("#")) {
70                 TreeNode node = new TreeNode(Integer.parseInt(str[i]));
71                 if (isLeftChild) {
72                     list.get(index).left = node;
73                 } else {
74                     list.get(index).right = node;
75                 }
76                 list.add(node);
77             }
78             if (!isLeftChild) {
79                 index++;
80             }
81             isLeftChild = !isLeftChild;
82         }
83         return list.get(0);
84     }
85 }
View Code

 

数据流中位数 -- 返回A[(n - 1) / 2]的中位数

思路:大根堆和小根堆,小根堆size为0或者比小根堆堆顶元素小的数加入小根堆,否则加入大根堆。加入之后,进行一次调整使得小根堆的size总是等于大根堆的size或者小根堆的size等于大根堆的size + 1

 1 public class Solution {
 2     /*
 3      * @param nums: A list of integers
 4      * @return: the median of numbers
 5      */
 6     public int[] medianII(int[] nums) {
 7         // write your code here
 8         if (nums == null || nums.length == 0) {
 9             return new int[0];
10         }
11         int[] result = new int[nums.length];
12         PriorityQueue<Integer> maxHeap
13         = new PriorityQueue<Integer>(new Comparator<Integer>() {
14             public int compare(Integer a, Integer b) {
15                 return b - a;
16             }
17         });
18         PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
19         for (int i = 0; i < nums.length; i++) {
20             if (maxHeap.size() == 0 || nums[i] < maxHeap.peek()) {
21                 maxHeap.offer(nums[i]);
22             } else {
23                 minHeap.offer(nums[i]);
24             }
25             if (maxHeap.size() - minHeap.size() > 1) {
26                 minHeap.offer(maxHeap.poll());
27             } else if (minHeap.size() > maxHeap.size()) {
28                 maxHeap.offer(minHeap.poll());
29             }
30             result[i] = maxHeap.peek();
31         }
32         return result;
33     }
34 }
View Code

 

滑动窗口中位数

Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, find the median of the element inside the window at each moving. (If there are even numbers in the array, return the N/2-th number after sorting the element in the window. )

Have you met this question in a real interview? Yes
Example
For array [1,2,7,8,5], moving window size k = 3. return [2,7,7]

At first the window is at the start of the array like this

[ | 1,2,7 | ,8,5] , return the median 2;

then the window move one step forward.

[1, | 2,7,8 | ,5], return the median 7;

then the window move one step forward again.

[1,2, | 7,8,5 | ], return the median 7;
题目

思路:跟数据流中位数思路一样,只是只有当当前位置 >= k - 1时才开始每次都将中位数加入到结果集中,并且每次都要删除滑动窗口最前面的一个数,删除该数之后要重新调整大根堆和小根堆的size关系。

 1 public class Solution {
 2     /*
 3      * @param nums: A list of integers
 4      * @param k: An integer
 5      * @return: The median of the element inside the window at each moving
 6      */
 7     public List<Integer> medianSlidingWindow(int[] nums, int k) {
 8         // write your code here
 9         List<Integer> result = new ArrayList<>();
10         if (nums == null || nums.length == 0 || k < 1 || k > nums.length) {
11             return result;
12         }
13         PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>() {
14             public int compare(Integer a, Integer b) {
15                 return b - a;
16             } 
17         });
18         PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
19         for (int i = 0; i < nums.length; i++) {
20             if (maxHeap.size() == 0 || nums[i] < maxHeap.peek()) {
21                 maxHeap.offer(nums[i]);
22             } else {
23                 minHeap.offer(nums[i]);
24             }
25             if (maxHeap.size() > minHeap.size() + 1) {
26                 minHeap.offer(maxHeap.poll());
27             } else if (minHeap.size() > maxHeap.size()) {
28                 maxHeap.offer(minHeap.poll());
29             }
30             if (i >= k - 1) {
31                 result.add(maxHeap.peek());
32                 int num = nums[i - k + 1];
33                 if (num <= maxHeap.peek()) {
34                     maxHeap.remove(num);
35                 } else {
36                     minHeap.remove(num);
37                 }
38                 if (maxHeap.size() > minHeap.size() + 1) {
39                     minHeap.offer(maxHeap.poll());
40                 } else if (minHeap.size() > maxHeap.size()) {
41                     maxHeap.offer(minHeap.poll());
42                 }
43             }
44         }
45         return result;
46     }
47 }
View Code

 

滑动窗口最大值

思路:双端队列,存储可能的最大值。加入队列时,删除队列中比这个数小的元素;删除前面的元素时,如果前面的元素等于队列首元素则删除队列首元素。

时间复杂度是O(n),因为每个数只可能被操作最多两次,一次是加入队列的时候,一次是因为有别的更大数在后面,所以被扔掉,或者因为出了窗口而被扔掉

空间复杂度O(k),由于队列里只有窗口内的数,所以他们其实就是窗口内第一大,第二大,第三大...的数。

 1 public class Solution {
 2     /*
 3      * @param nums: A list of integers
 4      * @param k: An integer
 5      * @return: The maximum number inside the window at each moving
 6      */
 7     public ArrayList<Integer> maxSlidingWindow(int[] nums, int k) {
 8         // write your code here
 9         ArrayList<Integer> result = new ArrayList<>();
10         if (nums == null || nums.length == 0 || k < 1 || k > nums.length) {
11             return result;
12         }
13         Deque<Integer> deque = new ArrayDeque<Integer>();
14         for (int i = 0; i < k - 1; i++) {
15             inQueue(deque, nums[i]);
16         }
17         for (int i = k - 1; i < nums.length; i++) {
18             inQueue(deque, nums[i]);
19             result.add(deque.peekFirst());
20             outQueue(deque, nums[i - k + 1]);
21         }
22         return result;
23     }
24     public void inQueue(Deque<Integer> deque, int num) {
25         while (!deque.isEmpty() && num > deque.peekLast()) {
26             deque.pollLast();
27         }
28         deque.offerLast(num);
29     }
30     public void outQueue(Deque<Integer> deque, int num) {
31         if (num == deque.peekFirst()) {
32             deque.pollFirst();
33         }
34     }
35 };
View Code

 

Ugly Number I -- 判断一个数是不是丑数(丑数是指素因子只有2,3,5,特别的,1也是丑数)

思路:不断除以素因子2,3,5,看最后的结果是否等于1。注意,0要事先特殊处理,否则会死循环。

 1 public class Solution {
 2     /*
 3      * @param num: An integer
 4      * @return: true if num is an ugly number or false
 5      */
 6     public boolean isUgly(int num) {
 7         // write your code here
 8         if (num == 0) {
 9             return false;
10         }
11         while (num % 2 == 0) {
12             num = num / 2;
13         }
14         while (num % 3 == 0) {
15             num = num / 3;
16         }
17         while (num % 5 == 0) {
18             num = num / 5;
19         }
20         return num == 1;
21     }
22 }
View Code

 

Ugly Number II -- 求第n个丑数

思路I:小根堆 + Set,循环n次就可以得到第n个丑数。时间复杂度O(nlgn),空间复杂度O(n)。注意当前数 * 2 、3、5可能会超出int范围,所以小根堆和Set中存储的类型为Long而不是Integer

 1 public class Solution {
 2     /*
 3      * @param n: An integer
 4      * @return: the nth prime number as description.
 5      */
 6     public int nthUglyNumber(int n) {
 7         // write your code here
 8         if (n < 1) {
 9             return 0;
10         }
11         PriorityQueue<Long> pq = new PriorityQueue<Long>();
12         Set<Long> set = new HashSet<>();
13         pq.offer((long) 1);
14         set.add((long) 1);
15         long num = 1;
16         for (int i = 0; i < n; i++) {
17             num = pq.poll();
18             if (!set.contains(num * 2)) {
19                 pq.offer(num * 2);
20                 set.add(num * 2);
21             }
22             if (!set.contains(num * 3)) {
23                 pq.offer(num * 3);
24                 set.add(num * 3);
25             }
26             if (!set.contains(num * 5)) {
27                 pq.offer(num * 5);
28                 set.add(num * 5);
29             }
30         }
31         return (int) num;
32     }
33 }
View Code

思路II:p2,p3,p5分别记录乘以2,3,5之后恰好大于当前丑数的位置,然后每次生成下一个丑数时取p2 * 2,p3 * 3和p5 * 5的最小值。

 1 public class Solution {
 2     /*
 3      * @param n: An integer
 4      * @return: the nth prime number as description.
 5      */
 6     public int nthUglyNumber(int n) {
 7         // write your code here
 8         if (n < 1) {
 9             return 0;
10         }
11         int p2 = 0, p3 = 0, p5 = 0;
12         List<Integer> ugly = new ArrayList<>();
13         ugly.add(1);
14         for (int i = 1; i < n; i++) {
15             while (ugly.get(p2) * 2 <= ugly.get(i - 1)) {
16                 p2++;
17             }
18             while (ugly.get(p3) * 3 <= ugly.get(i - 1)) {
19                 p3++;
20             }
21             while (ugly.get(p5) * 5 <= ugly.get(i - 1)) {
22                 p5++;
23             }
24             ugly.add(Math.min(Math.min(ugly.get(p2) * 2, ugly.get(p3) * 3),
25                               ugly.get(p5) * 5));
26         }
27         return ugly.get(ugly.size() - 1);
28     }
29 }
View Code

 

 最近公共祖先 -- Lowest Common Ancestor(LCA)

思路:分治。在root为根的二叉树中找A,B的LCA: 如果找到了就返回这个LCA;如果只碰到A,就返回A;如果只碰到B,就返回B;如果都没有,就返回null

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: The root of the binary search tree.
17      * @param A: A TreeNode in a Binary.
18      * @param B: A TreeNode in a Binary.
19      * @return: Return the least common ancestor(LCA) of the two nodes.
20      */
21     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
22         // write your code here
23         if (root == null || A == root || B == root) {
24             return root;
25         }
26         TreeNode left = lowestCommonAncestor(root.left, A, B);
27         TreeNode right = lowestCommonAncestor(root.right, A, B);
28         if (left != null && right != null) {
29             return root;
30         }
31         if (left != null) {
32             return left;
33         }
34         if (right != null) {
35             return right;
36         }
37         return null;
38     }
39 }
View Code

 

Digit Counts

Count the number of k's between 0 and n. k can be 0 - 9.
题目

思路I:暴力法,从0 - n对每一个数字计算k出现的次数,然后求和,注意n == 0 && k == 0的特殊情况处理

 1 public class Solution {
 2     /*
 3      * @param : An integer
 4      * @param : An integer
 5      * @return: An integer denote the count of digit k in 1..n
 6      */
 7     public int digitCounts(int k, int n) {
 8         // write your code here
 9         if (k < 0 || k > 9 || n < 0) {
10             return 0;
11         }
12         int num = 0;
13         for (int i = 0; i <= n; i++) {
14             num += count(i, k);
15         }
16         return num;
17     }
18     public int count(int n, int k) {
19         if (n == 0 && k == 0) {
20             return 1;
21         }
22         int count = 0;
23         while (n != 0) {
24             if (n % 10 == k) {
25                 count++;
26             }
27             n = n / 10;
28         }
29         return count;
30     }
31 };
View Code

思路II:

当某一位的数字小于i时,那么该位出现i的次数为:更高位数字x当前位数

当某一位的数字等于i时,那么该位出现i的次数为:更高位数字x当前位数+低位数字+1

当某一位的数字大于i时,那么该位出现i的次数为:(更高位数字+1)x当前位数

比如计算0到11间出现的0的次数,会把1,2,3,4…视为01,02,03,04… 从而得出错误的结果。所以0是需要单独考虑的。

注意n == 0 && k == 0的特殊情况处理

 1 public class Solution {
 2     /*
 3      * @param : An integer
 4      * @param : An integer
 5      * @return: An integer denote the count of digit k in 1..n
 6      */
 7     public int digitCounts(int k, int n) {
 8         // write your code here
 9         if (k < 0 || k > 9 || n < 0) {
10             return 0;
11         }
12         if (n == 0 && k == 0) {
13             return 1;
14         }
15         int factor = 1;
16         int low = 0, cur = 0, high = 0;
17         int count = 0;
18         while (n / factor != 0) {
19             low = n % factor;
20             cur = (n / factor) % 10;
21             high = n / (factor * 10);
22             if (cur < k) {
23                 count += high * factor;
24             } else if (cur == k) {
25                 count += high * factor + low + 1;
26             } else {
27                 count += (high + 1) * factor;
28             }
29             if (k == 0 && factor != 1) {
30                 count -= factor;
31             }
32             factor *= 10;
33         }
34         return count;
35     }
36 };
View Code

 

String to Integer II -- 将字符串转化成整数

Implement function atoi to convert a string to an integer.

If no valid conversion could be performed, a zero value is returned.

If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Have you met this question in a real interview? Yes
Example
"10" => 10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1
题目

思路:用一个flag标记是整数还是负数,需要处理很多特殊情况:空格(先trim)、判断第一个字符是不是'-'号,移动相应的start指针、累加过程中累加和sum可能会超出int范围,所以累加和sum定义为long、累加和 > Integer.MAX_VALUE + 1和累加和 == Integer.MIN_VALUE + 1这两种情况的特殊处理,因为int的范围是-2147483648 - 2147483647,所以要分> Integer.MAX_VALUE + 1和== Integer.MIN_VALUE + 1这两种情况。

 1 public class Solution {
 2     /*
 3      * @param str: A string
 4      * @return: An integer
 5      */
 6     public int atoi(String str) {
 7         // write your code here
 8         if (str == null || str.length() == 0) {
 9             return 0;
10         }
11         str = str.trim();
12         if (str.length() == 0) {
13             return 0;
14         }
15         boolean flag = true;
16         int start = 0;
17         if (str.charAt(0) == '-') {
18             flag = false;
19             start++;
20         } else if (str.charAt(0) == '+') {
21             start++;
22         }
23         long sum = 0;
24         while (start < str.length()
25                && str.charAt(start) >= '0' && str.charAt(start) <= '9') {
26             sum = sum * 10 + (str.charAt(start) - '0');
27             if (sum > (long) Integer.MAX_VALUE + 1) {
28                 if (flag) {
29                     return Integer.MAX_VALUE;
30                 } else {
31                     return Integer.MIN_VALUE;
32                 }
33             }
34             if (sum == (long) Integer.MAX_VALUE + 1) {
35                 if (flag) {
36                     return Integer.MAX_VALUE;
37                 }
38             }
39             start++;
40         }
41         if (!flag) {
42             sum = -sum;
43         }
44         return (int) sum;
45     }
46 }
View Code

 

Regular Expression Matching -- 正则表达式匹配

Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
题目

思路:

f[i][j]: if s[0..i-1] matches p[0..j-1]

if p[j - 1] != '*'

  f[i][j] = f[i - 1][j - 1] && s[i - 1] == p[j - 1]

if p[j - 1] == '*', denote p[j - 2] with x

  f[i][j] is true iff any of the following is true

    1) "x*" repeats 0 time and matches empty: f[i][j - 2]

    2) "x*" repeats >= 1 times and matches "x*x": s[i - 1] == x && f[i - 1][j]

 

 1 class Solution {
 2     public boolean isMatch(String s, String p) {
 3         if (s == null && p == null) {
 4             return true;
 5         }
 6         if (s == null || p == null) {
 7             return false;
 8         }
 9         int n = s.length();
10         int m = p.length();
11         if (m == 0) {
12             if (n == 0) {
13                 return true;
14             } else {
15                 return false;
16             }
17         }
18         boolean[][] dp = new boolean[n + 1][m + 1];
19         dp[0][0] = true;
20         for (int i = 1; i <= n; i++) {
21             dp[i][0] = false;
22         }
23         for (int j = 1; j <= m; j++) {
24             dp[0][j] = j > 1 && p.charAt(j - 1) == '*' && dp[0][j - 2];
25         }
26         for (int i = 1; i <= n; i++) {
27             dp[i][1] = i == 1 && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.');
28         }
29         for (int i = 1; i <= n; i++) {
30             for (int j = 2; j <= m; j++) {
31                 if (p.charAt(j - 1) != '*') {
32                     dp[i][j] = dp[i - 1][j - 1] && (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '.');
33                 } else {
34                     dp[i][j] = dp[i][j - 2] ||
35                                ((s.charAt(i - 1) == p.charAt(j - 2) || p.charAt(j - 2) == '.') && dp[i - 1][j]);
36                 }
37             }
38         }
39         return dp[n][m];
40     }
41 }
View Code

 

Symmetric Tree

判断一个二叉树是不是对称的二叉树

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public boolean isSymmetric(TreeNode root) {
12         if (root == null) {
13             return true;
14         }
15         return compare(root, root);
16     }
17     public boolean compare(TreeNode node1, TreeNode node2) {
18         if (node1 == null && node2 == null) {
19             return true;
20         }
21         if (node1 == null || node2 == null) {
22             return false;
23         }
24         if (node1.val != node2.val) {
25             return false;
26         }
27         return compare(node1.left, node2.right) && compare(node1.right, node2.left);
28     }
29 }
View Code

 

posted @ 2017-01-15 09:59  揪萌striving  阅读(308)  评论(0编辑  收藏  举报