1.数组中重复的数字
题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
解题思路
首先因为要求的时间复杂度是O(n),空间复杂度是O(1),所以不能使用基于排序的方法,对于这种[0 - n-1]的问题,可以将i的元素调整到i位置上。本题要求找出重复的数字,因此在调整过程中,如果第 i 位置上已经有一个值为 i 的元素,就可以知道 i 值重复。
public boolean duplicate(int nums[],int length,int [] duplication) {
if (nums == null || nums.length == 0) return false;
for (int i = 0; i < nums.length; i++) {
while (nums[i] != i) {
if (nums[i] == nums[nums[i]]) {
duplication[0] = nums[i];
return true;
}
swap(nums,i, nums[i]);
}
}
return false;
}
private void swap(int[] nums,int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
2.二维数组的查找
题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
解题思路
因为数组的每一行是升序的,每一列也是升序的,可以制定一个初始位置——左上角,如果当前元素小于左上角的元素就往左搜索,如果大于左上角的元素,就往下搜索。
public boolean Find(int target, int [][] array) {
if (array == null || array.length == 0) {
return false;
}
int rows = array.length;
int cols = array[0].length;
int curR = 0;
int curC = cols - 1;
while (curR < rows && curC >= 0) {
if (array[curR][curC] == target) {
return true;
}else if (array[curR][curC] > target) {
curC--;
}else {
curR++;
}
}
return false;
}
3.替换空格
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解题思路
第一种采用直接遍历原先的字符串。判断当前位置是否为’ ',主要存在的问题是会穿件新的字符串而不是在原来的字符串上操作。
第二种方式 :
- 先第一遍遍历字符,遇到一个空字符则在字符串的末尾添加添加2个空字符(因为%20比空字符多两个字符)
2.第二遍的时候设置两个指针一个p1指针指向添加后的字符串,一个指针p2指向原来字符串的末尾,p1 ,p2 从后往前遍历,p1遍历到一个空字符,p2就填充一个%20否则就填充上 P1 指向字符的值。
public String replaceSpace(StringBuffer str) {
StringBuffer sb=new StringBuffer();
for(int i=0;i<str.length();i++){
if(str.charAt(i)==' '){
sb.append("%20");
}else{
sb.append(str.charAt(i));
}
}
return sb.toString();
}
public String replaceSpace(StringBuffer str) {
int p1 = str.length() - 1;
for (int i = 0; i <= p1; i++){
if (str.charAt(i) == ' ') {
str.append(" ");
}
}
int p2 = str.length() - 1;
while (p1 >= 0 && p2 > p1) {
char c = str.charAt(p1--);
if (c == ' ') {
str.setCharAt(p2--,'0');
str.setCharAt(p2--,'2');
str.setCharAt(p2--,'%');
}else {
str.setCharAt(p2--,c);
}
}
return str.toString();
}
4.从头到尾打印链表(反转链表)
题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
解题方法
1.直接使用递归的方式:
要逆序打印链表 1->2->3(3,2,1),可以先逆序打印链表 2->3(3,2),最后再打印第一个节点 1。而链表 2->3 可以看成一个新的链表,要逆序打印该链表可以继续使用求解函数,也就是在求解函数中调用自己,这就是递归函数。
2.使用头插法反转链表再添加
3.使用栈
public ArrayList<Integer> printListFromTailToHead(ListNode head) {
ArrayList<Integer> res = new ArrayList<>();
if (head != null) {
//打印 1 2 3 先去打印2 3 然后再添加1的值
res.addAll(printListFromTailToHead(head.next));
res.add(head.val);
}
return res;
}
//头插法反转链表
public ArrayList<Integer> printListFromTailToHead(ListNode head) {
ArrayList<Integer> res = new ArrayList<>();
if (head == null) {
return res;
}
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
while (pre != null) {
res.add(pre.val);
pre = pre.next;
}
return res;
}
//使用栈
public ArrayList<Integer> printListFromTailToHead(ListNode head) {
ArrayList<Integer> res = new ArrayList<>();
if(res == null) return res;
Stack<Integer> stack = new Stack<>();
ListNode cur = head;
while (cur != null) {
stack.add(cur.val);
cur = cur.next;
}
while (!stack.isEmpty()) {
res.add(stack.pop());
}
return res;
}
5.重建二叉树
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题方法
前序遍历的第一个数代表这个树的根节点,在中序遍历的数组中找到根节点,这个位置的左边就代表这棵树的左子树,右边就是这棵树的右子树,再递归的区创建左子树和右子树。
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
return buildTree(pre, 0 , pre.length - 1, in, 0 ,in.length - 1);
}
private TreeNode buildTree (int[] pre, int preLeft, int preRight, int[] in, int inLeft, int inRight) {
if (preLeft > preRight || inLeft > inRight) {
return null;
}
TreeNode root = new TreeNode(pre[preLeft]);
for (int i = inLeft; i <= inRight; i++) {
if (in[i] == root.val) {
root.left = buildTree(pre, preLeft + 1, preLeft + i - inLeft, in, inLeft, i - 1);
root.right = buildTree(pre, preLeft + i - inLeft + 1, preRight, in, i + 1, inRight);
}
}
return root;
}
6.二叉树的下一个节点
题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null; //指向父节点
TreeLinkNode(int val) {
this.val = val;
}
}
解题方法
1.如的它的右子树不为空,则其下一个节点是其右子树的最左节点
2.如果它的右子树为空,则先找到他的父节点,如果他是他父节点的左孩子,则父节点就是他的下一个节点,如果不是,则不断的向上查找
public TreeLinkNode GetNext(TreeLinkNode pNode){
if (pNode == null) return null;
if (pNode.right != null) {
TreeLinkNode node = pNode.right;
while (node.left != null) {
node = node.left;
}
return node;
}else {
while (pNode.next != null) {
TreeLinkNode parent = pNode.next;
if (parent.left == pNode) return parent;
pNode = parent;
}
}
return null;
}
7. 用两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题方法
data栈专门用于push操作,当需要pop操作的时候先判断help栈中是否存在元素如果存在则直接pop help栈,如果不存在的话就先data栈中的所有元素导入help栈中。
Stack<Integer> data = new Stack<Integer>();
Stack<Integer> help = new Stack<Integer>();
public void push(int node) {
data.push(node);
}
public int pop() {
if (help.isEmpty()) {
while (!data.isEmpty()) {
help.push(data.pop());
}
}
return help.pop();
}
补充 : 两个队列实现栈
用两个队列实现栈,data栈用来存放元素,help栈用来辅助pop 和 peek操作,每当需要 pop 或者peek操作的时候,需要将data的元素先转移到help中,只留下最后一个元素作为返回值,然后交换引用。
private Queue<Integer> data = new LinkedList<>();
private Queue<Integer> help = new LinkedList<>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
data.offer(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
while (data.size() > 1) {
help.offer(data.poll());
}
int res = data.poll();
Queue temp = data;
data = help;
help = temp;
return res;
}
/** Get the top element. */
public int top() {
while (data.size() > 1) {
help.offer(data.poll());
}
int res = data.peek();
help.offer(data.poll());
Queue temp = data;
data = help;
help = temp;
return res;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return data.isEmpty();
}
8.1斐波那契数列
题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。 n<=39
解题方法
public int Fibonacci(int n) {
if (n <= 1) return n;
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
8.2 矩形覆盖
题目描述
我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
解题思路
要覆盖 2 * n 的矩形 可以先覆盖 2 * 1 的矩形,在覆盖 2 * ( n - 1)的矩形
或者先覆盖 2 * 2的矩形 再覆盖 2 * ( n - 2)的矩形
public int RectCover(int n) {
if (n <= 2) return n;
int pre2 = 1;
int pre1 = 2;
int result = 0;
for (int i = 3; i <= n; i++) {
result = pre1 + pre2;
pre2 = pre1;
pre1 = result;
}
return result;
}
8.3 跳台阶
题目描述
一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
解题方法
public int JumpFloor(int n) {
if (n <= 2)
return n;
int pre2 = 1, pre1 = 2;
int result = 0;
for (int i = 2; i < n; i++) {
result = pre2 + pre1;
pre2 = pre1;
pre1 = result;
}
return result;
}
8.4 变态跳台阶
题目描述
一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级… 它也可以跳上 n 级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
解题方法
跳上 n 级台阶,可以从 n-1 级跳 1 级上去,也可以从 n-2 级跳 2 级上去…
f (n) = f(n - 1) + f(n - 2) + f(n - 3 ) + … + f(0)
f (n - 1) = f(n - 2 ) + f(n - 3) + f(n - 4) + … + f(0)
f(n) = 2 * f(n - 1)
等比数列
public int JumpFloorII(int target) {
return (int)(Math.pow(2, target - 1));
}
9 旋转数组的最小数字
题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
解题思路
二分法查找,如果中间的元素大于右边的元素,那么后半部分逆序,最小值就出现在后半部分,否则最小值出现在左半部分
存在元素都相等的情况 就缩小右边界 过滤掉重复的元素
public int minNumberInRotateArray(int [] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] == nums[right]) {
right = right - 1;
}else if (nums[mid] > nums[right]) {
left = mid + 1;
}else {
right = mid;
}
}
return nums[left];
}
10 矩阵中的路径
题目描述
解题思路
使用回溯法,回溯是一种暴力搜索的算法,是dfs的一种。
回溯法在一次搜索结束时需要进行回溯(回退),将这一次搜索过程中设置的状态进行清除,从而开始一次新的搜索过程。例如下图示例中,从 f 开始,下一步有 4 种搜索可能,如果先搜索 b,需要将 b 标记为已经使用,防止重复使用。在这一次搜索结束之后,需要将 b 的已经使用状态清除,并搜索 c
在f位置时不会往b方向搜索,因为b已经被标记为visited
private final static int[][] direction = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
private int rows;
private int cols;
public boolean hasPath(char[] array, int rows, int cols, char[] str){
if (rows == 0 || cols == 0) return false;
this.rows = rows;
this.cols = cols;
char[][] matrix = buildMatrix(array);
boolean[][] visited = new boolean[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (dfs(matrix,i,j,visited,str,0)) {
return true;
}
}
}
return false;
}
private boolean dfs(char[][] matrix, int i, int j, boolean[][] visited,char[] str,int start) {
if (start == str.length) {
return true;
}
if (i < 0 || i >= rows || j < 0 || j >= cols || matrix[i][j] != str[start] || visited[i][j]) {
return false;
}
visited[i][j] = true;
for (int[] dir : direction) {
int x = i + dir[0];
int y = j + dir[1];
if (dfs(matrix, x, y, visited, str, start + 1)) {
return true;
}
}
visited[i][j] = false;
return false;
}
private char[][] buildMatrix(char[] array) {
char[][] matrix = new char[rows][cols];
for (int r = 0, idx = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
matrix[r][c] = array[idx++];
return matrix;
}
11 机器人的运动范围
题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
解题思路
使用深度优先搜索(Depth First Search,DFS)方法进行求解。回溯是深度优先搜索的一种特例,它在一次搜索过程中需要设置一些本次搜索过程的局部状态,并在本次搜索结束之后清除状态。而普通的深度优先搜索并不需要使用这些局部状态,虽然还是有可能设置一些全局状态。
private int[][] direction = {{1,0},{-1,0},{0,-1},{0,1}};
private int rows;
private int cols;
private int threshold;
private int count = 0;
public int movingCount(int threshold, int rows, int cols) {
this.rows = rows;
this.cols = cols;
this.threshold = threshold;
boolean[][] visited = new boolean[rows][cols];
dfs(visited, 0, 0);
return count;
}
private void dfs(boolean[][] visited,int i, int j) {
if (i < 0 || i >= rows || j < 0 || j >= cols || visited[i][j]) {
return;
}
visited[i][j] = true;
if (getDigit(i) + getDigit(j) > threshold) {
return;
}
count++;
for (int[] dir : direction) {
int x = i + dir[0];
int y = j + dir[1];
dfs(visited, x, y);
}
}
private int getDigit(int number) {
int sum = 0;
while (number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
12、剪绳子
题目描述
给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1),每段绳子的长度记为k[0],k[1],…,k[m]。请问k[0]xk[1]x…xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
解题思路
动态规划
dp[i]代表i拆分之后得到的最大乘积
dp[i - j] * j 表示拆分i-j后的最大乘积,另外乘以拆分出去的的j。其实(等价于(i - j) * dp[j])
(i - j) * j 表示直接拆成(i - j)和j,所以没有后续(i - j)和j的各自拆分
dp[i] = Math.max(dp[i], Math.max(dp[i - j] * j,(i - j) * j )
public int cutRope(int target) {
int[] dp = new int[target + 1];
dp[1] = 1;
for (int i = 2; i <= target; i++) {
for (int j = 1; j < i; j++) {
dp[i] = Math.max(dp[i], Math.max(dp[i - j] * j, (i - j) * j));
}
}
return dp[target];
}
13、二进制中1的个数
题目描述
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
解题思路
一个数与n - 1与运算 可以移除末尾的1
n : 10110100
n-1 : 10110011
n&(n-1) : 10110000
public int NumberOf1(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
return count;
}
14、数值的整数次方
题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。保证base和exponent不同时为0
解题思路
首先判断指数是不是负数,如果是负数的话先得将指数变为正数。然后判断指数是偶数还是基数。
public double Power(double base, int exponent) {
if (exponent == 0) return 1;
if (exponent == 1) return base;
boolean isNagtive = false;
if (exponent < 0) {
isNagtive = true;
exponent = -exponent;
}
double res = Power(base * base,exponent / 2);
if (exponent % 2 != 0) {
res = base * res;
}
return isNagtive ? 1 / res : res;
}
15、在 O(1) 时间内删除链表节点
题目描述
请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
解题思路
如果不是末尾的节点的话 那么直接将其下一个节点的值赋予当前的节点,然后删除后面的节点即可
如果如末尾的节点,则需要遍历链表找到倒数第二个节点在删除最后一个
public ListNode deleteNode(ListNode head, ListNode tobeDelete) {
if (head == null || tobeDelete == null)
return null;
if (tobeDelete.next != null) {
// 要删除的节点不是尾节点
ListNode next = tobeDelete.next;
tobeDelete.val = next.val;
tobeDelete.next = next.next;
} else {
if (head == tobeDelete)
// 只有一个节点
head = null;
else {
ListNode cur = head;
while (cur.next != tobeDelete)
cur = cur.next;
cur.next = null;
}
}
return head;
}
15、删除链表中重复的节点
题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
解题思路
递归求解,如果当前根节点的值和其next节点值相等,则代表出现重复,循环找到第一个不相等的节点,将这些点删除。
如果不等的话,代表当前节点不删除,递归调用其next节点即可。
public ListNode deleteDuplication(ListNode pHead){
if (pHead == null || pHead.next == null) return pHead;
ListNode next = pHead.next;
if (pHead.val == next.val) {
while (next != null && pHead.val == next.val) {
next = next.next;
}
return deleteDuplication(next);
}else {
pHead.next = deleteDuplication(next);
return pHead;
}
}
16、正则表达式的匹配
题目描述
请实现一个函数用来匹配包括’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"abaca"匹配,但是与"aa.a"和"ab*a"均不匹配
解题思路
17、表示数值的字符串
题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
解题思路
//e不能出现在最后一个位置,e不能出现两次
//第一次出现±,且不是在字符串的开头,则也必须紧接在e之后,第二次出现+ 或者-号必须接在e的后面
有e了就不能刚在出现小数点,小数点也只能出现一次
public boolean isNumeric(char[] str) {
boolean sign = false;
boolean decimal = false;
boolean hasE = false;
for (int i = 0; i < str.length; i++) {
if (str[i] == 'e' || str[i] == 'E') {//出现e,E
if (i == str.length - 1)return false; //e不能出现在最后一个位置
if (hasE) return false;//前面已经出现过E, e
hasE = true;
}else if (str[i] == '+' || str[i] == '-') {
if (sign && str[i - 1] != 'e' && str[i - 1] != 'E') {
return false;//第二次出现+ 或者-号必须接在e的后面
}
if (!sign && i > 0 && str[i - 1] != 'e' && str[i - 1] != 'E') {
return false;//第一次出现+-,且不是在字符串的开头,则也必须紧接在e之后
}
sign = true;
}else if (str[i] == '.'){
if (hasE || decimal) return false;
decimal = true;
}else if (str[i] < '0' || str[i] > '9') {
return false;
}
}
return true;
}
17、调整数组顺序使奇数位于偶数前面
题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
解题思路
运用冒泡排序的思想,每一轮都将偶数上浮到最右边,判断的时候需要下一个节点是奇数再判断
public void reOrderArray(int [] array) {
int n = array.length - 1;
for (int i = n; i > 0; i--) {
for (int j = 0; j < i; j++) {
if ((array[j] % 2 == 0) && (array[j + 1] % 2 != 0)) {
swap(array, j , j + 1);
}
}
}
}
private void swap(int[] array, int i , int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
运用辅助空间,创建一个新的数组。
public void reOrderArray(int [] array) {
int oddCount = 0;
for (int x : array) {
if (x % 2 != 0) {
oddCount++;
}
}
int[] copy = array.clone();
int i = 0, j = oddCount;
for (int x : copy) {
if (x % 2 != 0) {
array[i++] = x;
}else {
array[j++] = x;
}
}
}
18.输入一个链表,输出该链表中倒数第k个结点。
题目描述
输入一个链表,输出该链表中倒数第k个结点。
解题思路
快慢指针,快指针先走k步,然后快慢指针一起走
public ListNode FindKthToTail(ListNode head,int k) {
if (head == null) return head;
ListNode fast = head;
while (fast != null && k -- > 0) {
fast = fast.next;
}
if (k > 0) {
return null;
}
ListNode slow = head;
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
19.链表的入环节点
题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
解题思路
快慢指针,快指针一次性走两步,慢指针一次走一步,当两个指针相遇的时候表明存在环,相遇之后快指针指向头结点,与慢指针一次都直走一步,直到两个节点相遇,就是入环的节点。
public ListNode EntryNodeOfLoop(ListNode head){
if (head == null) return head;
ListNode fast = head;
ListNode slow = head;
boolean flag = false;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
if (slow == fast) {
flag = true;
break;
}
}
if (flag) {
slow=head;
while(slow!=fast){
slow=slow.next;
fast=fast.next;
}
return fast;
}else {
return null;
}
}
20.反转链表
递归方法 !!!
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
head.next = null;
ListNode newHead = ReverseList(next);
next.next = head;
return newHead;
}
21. 合并两个排序的链表
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路
递归 迭代
public ListNode Merge(ListNode list1,ListNode list2) {
if (list1 == null) return list2;
if (list2 == null) return list1;
if (list1.val <= list2.val) {
list1.next = Merge(list1.next,list2);
return list1;
}else {
list2.next = Merge(list1,list2.next);
return list2;
}
}
public ListNode Merge(ListNode l1,ListNode l2) {
ListNode dummyHead = new ListNode(-1);
ListNode cur = dummyHead;
while (l1 != null && l2!= null) {
if (l1.val <= l2.val) {
cur.next = l1;
l1 = l1.next;
}else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if (l1 != null) {
cur.next = l1;
}
if (l2 != null) {
cur.next = l2;
}
return dummyHead.next;
}
22. 树的子结构
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
解题思路
先去判断以roo1为根的数是否与root为根的数相等,不想等的话再去递归的去判断root1的左子树与root和root1的右子树与root2是否相等
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null)
return false;
return isSubtreeWithRoot(root1, root2) || HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2);
}
private boolean isSubtreeWithRoot(TreeNode root1, TreeNode root2) {
if (root2 == null)
return true;
if (root1 == null)
return false;
if (root1.val != root2.val)
return false;
return isSubtreeWithRoot(root1.left, root2.left) && isSubtreeWithRoot(root1.right, root2.right);
}
23. 二叉树的镜像
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
解题思路
第交换根节点 再分别递归的去交换左子树右子树
public void Mirror(TreeNode root) {
if (root == null) {
return ;
}
swap(root);
Mirror(root.left);
Mirror(root.right);
}
private void swap(TreeNode root) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
24. 对称二叉树
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
解题思路
递归判断左右子树是否对称
boolean isSymmetrical(TreeNode root){
if (root == null) return true;
return isSame(root.left, root.right);
}
private boolean isSame(TreeNode left, TreeNode right) {
if (left == null && right == null) return true;
if (left == null || right == null) return false;
if (left.val != right.val) return false;
return isSame(left.left, right.right) && isSame(left.right, right.left);
}
25.顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
解题思路
定义一个打印数组值打印数组外层边界的函数
ArrayList<Integer> res = new ArrayList<>();
public ArrayList<Integer> printMatrix(int [][] matrix) {
if (matrix == null || matrix.length == 0) return res;
int tR = 0;
int tC = 0;
int dR = matrix.length - 1;
int dC = matrix[0].length - 1;
while (tR <= dR && tC <= dC) {
print(matrix, tR++, tC++,dR--,dC--);
}
return res;
}
private void print(int[][] matrix,int tR, int tC, int dR, int dC) {
if (tR == dR) {
for (int i = tC; i <= dC; i++) {
res.add(matrix[tR][i]);
}
}else if (tC == dC) {
for (int i = tR; i <= dR; i++) {
res.add(matrix[i][tC]);
}
}else {
int curR = tR;
int curC = tC;
while (curC != dC) {
res.add(matrix[curR][curC++]); //打印第一行
}
while (curR != dR) {
res.add(matrix[curR++][dC]); //打印最右边的那一列
}
while (curC != tC) {
res.add(matrix[dR][curC--]); //打印最底下的那一行
}
while (curR != tR) {
res.add(matrix[curR--][tC]); //打印最左边的那一行
}
}
}
26.包含min函数的最小栈
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
解题思路
要用到两个栈,一个栈用于存储数据,另一个用于存储最小值,当当前的元素比min栈栈顶小的时候,就压入min栈,否则就重复压入一个min栈栈顶的元素。
Stack<Integer> data = new Stack<>();
Stack<Integer> min = new Stack<>();
public void push(int node) {
data.push(node);
if (min.isEmpty() || node < min.peek()) {
min.push(node);
}else {
min.push(min.peek());
}
}
public void pop() {
data.pop();
min.pop();
}
public int top() {
return data.peek();
}
public int min() {
return min.peek();
}
27.栈的压入和弹出序列
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
解题思路
使用一个栈来模拟压入和弹出操作,不断的往栈中压入元素,直到遇到与pop数组顶部元素相等时候表明这个元素该pop了。
public boolean IsPopOrder(int [] pushA,int [] popA) {
if (pushA == null || popA == null || pushA.length != popA.length) return false;
int index = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < pushA.length; i++) {
stack.push(pushA[i]);
while (!stack.isEmpty() && stack.peek() == popA[index]) {
stack.pop();
index++;
}
}
return stack.isEmpty();
}
28.1.从上到下打印二叉树
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路
二叉树的层序遍历
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
res.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
return res;
}
28.2把二叉打印成多行
ArrayList<ArrayList<Integer> > res = new ArrayList<>();
ArrayList<ArrayList<Integer> > Print(TreeNode root) {
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
while (!queue.isEmpty()) {
int count = queue.size();
ArrayList<Integer> temp = new ArrayList<>();
while (count -- > 0) {
TreeNode node = queue.poll();
temp.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
res.add(temp);
}
return res;
}
28.3 之字形打印二叉树
定义一个变量标记上次打印用了什么顺序 + Collections.revers()操作
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public ArrayList<ArrayList<Integer>> Print(TreeNode root) {
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean flag = false;
while (!queue.isEmpty()) {
int count = queue.size();
ArrayList<Integer> temp = new ArrayList<>();
while (count -- > 0) {
TreeNode node = queue.poll();
temp.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
if (flag) {
Collections.reverse(temp);
}
flag = !flag;
res.add(temp);
}
return res;
}
29 BST的后续遍历序列
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
解题思路
后续遍历数组的最后一个位置即为根节点的值,以这个值为划分值,找到根节点的左孩子,左孩子全部小于根节点,在判断右还是是不是全部大于根节点。
public boolean VerifySquenceOfBST(int [] sequence) {
if (sequence == null || sequence.length == 0) return false;
return isBST(sequence,0,sequence.length - 1);
}
private boolean isBST(int[] sequence, int first, int last) {
if (first >= last) return true;
int root = sequence[last];
int index = first;
while (index < last && sequence[index] < sequence[last]) {
index++;
}
for (int i = index; i < last; i++) {
if (root > sequence[i]) return false;
}
return isBST(sequence,first,index - 1) && isBST(sequence,index,last - 1);
}
30 二叉树中和为某一值的路径
题目描述
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
解题思路
dfs深度遍历,几个注意点 1. res.add(new ArrayList<>(path)); 2.
path.remove(path.size() - 1);
得到一个结果只收不要retrun
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if (root == null) return res;
ArrayList<Integer> path = new ArrayList<>();
find(root,path,target);
return res;
}
private void find (TreeNode root, ArrayList<Integer> path,int target) {
if (root == null) return ;
path.add(root.val);
target -= root.val;
if (target == 0 && root.left == null && root.right == null) {
res.add(new ArrayList<>(path)); //此处不需要return
}
find(root.left,path,target);
find(root.right,path,target);
path.remove(path.size() - 1);
}
31 、复杂链表的复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
解题思路
分为三步 1.复制链表 2. 复制随机指针 3. 拆分链表!!!判断的时候是 cur.next != null
public RandomListNode Clone(RandomListNode head){
if (head == null) return head;
RandomListNode cur = head;
while (cur != null) {
RandomListNode clone = new RandomListNode(cur.label);
RandomListNode next = cur.next;
cur.next = clone;
clone.next = next;
cur = next;
}
cur = head;
while (cur != null) {
RandomListNode clone = cur.next;
if (cur.random != null){
clone.random = cur.random.next;
}
cur = clone.next;
}
cur = head;
RandomListNode newHead = cur.next;
while (cur.next != null) {
RandomListNode next = cur.next;
cur.next = next.next;
cur = next;
}
return newHead;
}
32、 二叉搜索树与排序链表
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
解题思路
定义两个全局的变量 pre 用来表示前一个节点 和 head 用来表示头结点再结合中序遍历
TreeNode pre = null;
TreeNode head = null;
public TreeNode Convert(TreeNode root) {
if (root == null) return root;
inOrder(root);
return head;
}
private void inOrder(TreeNode root) {
if (root == null) return ;
inOrder(root.left);
root.left = pre;
if (pre != null) {
pre.right = root;
}
pre = root;
if (head == null) {
head = root;
}
inOrder(root.right);
}
33、 序列化二叉树
题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。
二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。
解题思路
用什么方式序列化 就需要用什么方式反序列化,在反序列化的时候注意需要先将字符串拆分成字符数组,并用 队列 去存储。
String Serialize(TreeNode root) {
if (root == null) {
return "#,";
}
StringBuffer sb = new StringBuffer();
sb.append(root.val + ",");
sb.append(Serialize(root.left));
sb.append(Serialize(root.right));
return sb.toString();
}
TreeNode Deserialize(String str) {
if (str == null) return null;
String[] strArr = str.split(",");
Queue<String> queue = new LinkedList<>();
for (int i = 0; i < strArr.length; i++) {
queue.offer(strArr[i]); //用队列存储!!!
}
return bulidTree(queue);
}
TreeNode bulidTree(Queue<String> queue) {
String str = queue.poll();
if (str.equals("#")) {
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(str));
root.left = bulidTree(queue);
root.right = bulidTree(queue);
return root;
}
34、 字符串的排列组合
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
解题思路
排列组合问题!!! 很重要
ArrayList<String> res = new ArrayList<>();
public ArrayList<String> Permutation(String str) {
if (str == null || str.length() == 0) return res;
char[] strArr = str.toCharArray();
Arrays.sort(strArr);
boolean[] used = new boolean[strArr.length];
generatePerimutation(strArr,used,new StringBuffer());
return res;
}
private void generatePerimutation(char[] arr,boolean[] used,StringBuffer temp) {
if (temp.length() == arr.length) {
res.add(temp.toString());
return;
}
for (int i = 0; i < arr.length; i++) {
if (used[i])continue;
if (i != 0 && arr[i] == arr[i - 1] && used[i - 1]){
continue;
}
used[i] = true;
temp.append(arr[i]);
generatePerimutation(arr,used,temp);
temp.deleteCharAt(temp.length() - 1);
used[i] = false;
}
}
35、 数组中超过一半的数字
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
解题思路
摩尔投票法: 使用 cnt 来统计一个元素出现的次数,当遍历到的元素和统计元素相等时,令 cnt++,否则令 cnt–。如果前面查找了 i 个元素,且 cnt == 0,说明前 i 个元素没有 majority,或者有 majority,但是出现的次数少于 i / 2 ,因为如果多于 i / 2 的话 cnt 就一定不会为 0 。此时剩下的 n - i 个元素中,majority 的数目依然多于 (n - i) / 2,因此继续查找就能找出 majority。
最后的res有两种可能 一种就是res 一种是最后一个数字(如果前面都没有重复的值),还需在进行一次判断
public int MoreThanHalfNum_Solution(int [] array) {
int res = array[0];
for (int i = 1,count = 1; i < array.length; i++) {
count = array[i] == res ? count + 1 : count - 1;
if (count == 0) {
res = array[i];
count = 1;
}
}
int count = 0;
for (int num : array) {
if (num == res) {
count++;
}
}
return count * 2 > array.length ? res : 0;
}
36、最小的k个数
题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
解题思路
public ArrayList<Integer> GetLeastNumbers_Solution(int [] nums, int k) {
ArrayList<Integer> res = new ArrayList<>();
if (k > nums.length || k <= 0) {
return res;
}
find_kthSmall(nums, k - 1);
for (int i = 0; i < k; i++) {
res.add(nums[i]);
}
return res;
}
public void find_kthSmall(int[] nums, int k) {
int l = 0;
int r = nums.length - 1;
while (l < r) {
int[] p = partition(nums, l, r);
int j = p[0];
if (j == k) break;//如果等于区域的左边界直接和k相等了,那么说明前面就是k小个数
if (j > k) r = j - 1;
if (j < k) l = j + 1;
}
}
private int[] partition(int[] arr, int left, int right) {
int less = left - 1;
int more = right + 1;
int value = arr[right];
int cur = left;
while (cur < more) {
if (arr[cur] < value) {
swap(arr, ++left, cur++);
}else if (arr[cur] > value) {
swap(arr, --more, cur);
}else{
cur++;
}
}
return new int[]{less + 1, more - 1};//返回等于区域的边界,和等于区域的右边界
}
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
基于大根堆的解法 PriorityQueue默认是小根堆!!! 还有lambda表达式的写法(o1, o2) -> o2 - o1,维护一个大小为k的大根堆,堆顶的元素即为这k个数中的最大值,如果后加入的元素比堆顶元素小进行一次替换。
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> res = new ArrayList<>();
if(input == null || k ==0 || k > input.length)return res;
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1, o2) -> o2 - o1);
for (int i = 0; i < input.length; i++) {
if (maxHeap.size() != k){
maxHeap.offer(input[i]);
}else if (input[i] < maxHeap.peek()) {
maxHeap.poll();
maxHeap.offer(input[i]);
}
}
for(Integer i:maxHeap){
res.add(i);
}
return res;
}
37 数据流中的中位数
题目描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数
解题思路
大顶堆,用于存储左半边的元素
小顶堆,存储右半边的元素,并且右半边的元素都大于左半边count 为当前数据流读入的元素的个数
插入的时候需要保持两个堆的状态
N为偶数的时候插入到右半边,因为右半边的元素都大于左半边,但是新插入元素不一定比左半边元素来的大,因此需要先将元素插入到左半边,然后利用左半边为大顶堆的特点,取出对顶元素即为左半边的最大的元素,此时插入到右半边
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1,o2) -> o2 - o1);
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
private int count = 0;
public void Insert(Integer num) {
if (count % 2 == 0) {
maxHeap.add(num);
minHeap.add(maxHeap.poll());
}else {
minHeap.add(num);
maxHeap.add(minHeap.poll());
}
count++;
}
public Double GetMedian() {
if (count % 2 == 0) {
return (minHeap.peek() + maxHeap.peek()) / 2.0;
}else {
return (double) minHeap.peek();
}
}
38 字符流中第一个不重复的字符
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
解题思路
队列的头部始终是第一个不重复的元素,每当来一个元素的时候,先记录下其出现的个数,并放入队列中,每次都要判断队列头部的元素是否重复了。
private int[] cnts=new int[256];
private Queue<Character> queue=new LinkedList<>();
//Insert one char from stringstream
public void Insert(char ch){
cnts[ch]++;
queue.add(ch);
while(!queue.isEmpty()&&cnts[queue.peek()]>1){
queue.poll();
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce(){
return queue.isEmpty()?'#':queue.peek();
}
39 连续子数组的最大和
public int FindGreatestSumOfSubArray(int[] array) {
if (array == null || array.length == 0) return 0;
int curSum = array[0];
int maxSum = array[0];
for (int i = 1; i < array.length; i++) {
curSum = Math.max(array[i], curSum + array[i]);
maxSum = Math.max(curSum , maxSum);
}
return maxSum;
}
40 . 从 1 到 n 整数中 1 出现的次数
题目描述
求出113的整数中1出现的次数,并算出1001300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1
到 n 中1出现的次数)。
public int NumberOf1Between1AndN_Solution(int n) {
int cnt = 0;
for (int m = 1; m <= n; m *= 10) {
int a = n / m, b = n % m;
cnt += (a + 8) / 10 * m + (a % 10 == 1 ? b + 1 : 0);
}
return cnt;
}
41 把数组排成最小的数
题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
if (numbers == null || numbers.length == 0) return "";
String[] strArr = new String[numbers.length];
for (int i = 0; i < strArr.length; i++) {
strArr[i] = numbers[i] + "";
}
Arrays.sort(strArr,(s1,s2) -> (s1 + s2).compareTo(s2 + s1));
StringBuffer sb = new StringBuffer();
for (String str : strArr) {
sb.append(str);
}
return sb.toString();
42 把数字翻译成字符串
题目描述
给定一个数字,按照如下规则翻译成字符串:1 翻译成“a”,2 翻译成“b”… 26 翻译成“z”。一个数字有多种翻译可能,例如 12258 一共有 5 种,分别是 abbeh,lbeh,aveh,abyh,lyh。实现一个函数,用来计算一个数字有多少种不同的翻译方法。
解题思路
从后往前遍历。如果
以22067为例,从后往前遍历。
首先如果为7。很显然是1种7->G
如果为67。很显然还是1种67->FG
如果为067。结果为0。
如果为2067。 结果为numDecodings(20 67)+ numDecodings(2 067)= numDecodings(20 67)->TFG
如果为22067。 结果为numDecodings(2 2067)+ numDecodings(22 067)= numDecodings(2 2067)->BTFG
从中,我们可以看出规律。
如果开始的数为0,结果为0。
如果开始的数加上第二个数小于等于26。结果为 numDecodings(start+1)+ numDecodings(start +2)
如果开始的数加上第二个数大于26。结果为 numDecodings(start +1)
public int numDecodings(String s) {
if (s == null || s.length() == 0) return 0;
int len = s.length();
int[] dp = new int[len + 1];
dp[len] = 1;
dp[len - 1] = s.charAt(len - 1) == '0' ? 0 : 1;
for (int i = len - 2; i >= 0; i--) {
if (s.charAt(i) == '0') {
dp[i] = 0;
continue;
}
if ((s.charAt(i) - '0') * 10 + (s.charAt(i + 1) - '0') <= 26) {
dp[i] = dp[i + 1] + dp[i + 2];
}else {
dp[i] = dp[i + 1];
}
}
return dp[0];
}
43、礼物的最大价值
题目描述
小东所在公司要发年终奖,而小东恰好获得了最高福利,他要在公司年会上参与一个抽奖游戏,游戏在一个66的棋盘上进行,上面放着36个价值不等的礼物,每个小的棋盘上面放置着一个礼物,他需要从左上角开始游戏,每次只能向下或者向右移动一步,到达右下角停止,一路上的格子里的礼物小东都能拿到,请设计一个算法使小东拿到价值最高的礼物。给定一个66的矩阵board,其中每个元素为对应格子的礼物价值,左上角为[0,0],请返回能获得的最大价值,保证每个礼物价值大于100小于1000。
public int getMost(int[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) return 0;
int m = board.length - 1;
int n = board[0].length - 1;
int dp[][] = new int[m + 1][n + 1];
dp[m][n] = board[m][n];
for (int i = m - 1; i >= 0; i--) {
dp[i][n] = board[i][n] + dp[i + 1][n];
}
for (int j = n - 1; j >= 0; j--) {
dp[m][j] = board[m][j] + dp[m][j + 1];
}
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
dp[i][j] = board[i][j] + Math.max(dp[i + 1][j], dp[i][j + 1]);
}
}
return dp[0][0];
}
45、最长不含重复字符的子字符串
滑动窗口 加上set判断重复
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() < 0)return 0;
int res = 0;
Set<Character> set = new HashSet<>();
for (int left = 0, right = 0; right < s.length(); right++) {
char c = s.charAt(right);
while (set.contains(c)) {
set.remove(s.charAt(left++));
}
set.add(c);
res = Math.max(res,right - left + 1);
}
return res;
}
}
46、丑数
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
public int GetUglyNumber_Solution(int N) {
if (N <= 6) return N;
int index2 = 0;
int index3 = 0;
int index5 = 0;
int[] dp = new int[N];
dp[0] = 1;
for (int i = 1; i < N; i++) {
int next2 = dp[index2] * 2;
int next3 = dp[index3] * 3;
int next5 = dp[index5] * 5;
dp[i] = Math.min(next2, Math.min(next3, next5));
if (dp[i] == next2)index2++;
if (dp[i] == next3)index3++;
if (dp[i] == next5)index5++;
}
return dp[N - 1];
}
47、第一个只出现一次的字符位置
题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)
public int FirstNotRepeatingChar(String str) {
int[] cnts = new int[256];
for (int i = 0; i < str.length(); i++)
cnts[str.charAt(i)]++;
for (int i = 0; i < str.length(); i++)
if (cnts[str.charAt(i)] == 1)
return i;
return -1;
}
48、数组中的逆序对
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
解题思路
在归并排序最后的merge过程中统计逆序的次数
this.count += mid - p1 + 1;代表这个数的右边的值 都大于右半边那个数字 组成逆序对
private long count;
public int InversePairs(int[] nums) {
if (nums == null || nums.length == 0) return 0;
mergeSort(nums, 0 , nums.length - 1);
return (int) (count % 1000000007);
}
private void mergeSort(int[] nums, int left , int right) {
if (left >= right) {
return ;
}
int mid = left + (right - left) / 2;
mergeSort(nums, left, mid);
mergeSort(nums, mid + 1, right);
merge(nums, left, mid, right);
}
private void merge(int[] nums, int left, int mid, int right) {
int[] help = new int[right - left + 1];
int index = 0;
int p1 = left;
int p2 = mid + 1;
while (p1 <= mid && p2 <= right) {
if (nums[p1] <= nums[p2]){
help[index++] = nums[p1++];
}else {
help[index++] = nums[p2++];
this.count += mid - p1 + 1;
}
}
while (p1 <= mid) {
help[index++] = nums[p1++];
}
while (p2 <= right) {
help[index++] = nums[p2++];
}
for (int i = 0; i < help.length; i++) {
nums[left + i] = help[i];
}
}
49、两个链表的第一个公共的节点
题目描述
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
解题思路
设 A 的长度为 a + c,B 的长度为 b + c,其中 c 为尾部公共部分长度,可知 a + c + b = b + c + a。
当访问链表 A 的指针访问到链表尾部时,令它从链表 B 的头部重新开始访问链表 B;同样地,当访问链表 B 的指针访问到链表尾部时,令它从链表 A 的头部重新开始访问链表 A。这样就能控制访问 A 和 B 两个链表的指针能同时访问到交点。
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode l1 = pHead1;
ListNode l2 = pHead2;
while (l1 != l2) {
l1 = l1 == null ? pHead2 : l1.next;
l2 = l2 == null ? pHead1 : l2.next;
}
return l1;
}
50、数字在排序数组中出现的次数
题目描述
统计一个数字在排序数组中出现的次数。
解题思路
二分的查找k的左边界 和k +1 的左边界
left = 0, right = arr.length
当left = right时候退出
1.此时有可能没有找到left = array.length
2.或者找到的边界不是k的值 left == right == 0;
public int GetNumberOfK(int [] array , int k) {
int first = binarySearch(array, k);
int last = binarySearch(array, k + 1);
return (first == array.length || array[first] != k) ? 0 : last - first;
}
private int binarySearch(int[] nums, int target) {
int left = 0;
int right = nums.length;
while (left < right) { //当left = right时候退出
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid;
}else {
left = mid + 1;
}
}
return left;
}
51、二叉查找树的第k个节点
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
解题思路
中序遍历的时候添加一个计数器
TreeNode res = null;
private int count = 0;
TreeNode KthNode(TreeNode pRoot, int k){
if (pRoot == null) return res;
inOrder(pRoot, k);
return res;
}
private void inOrder(TreeNode root, int k) {
if (root == null || count > k) return;
inOrder(root.left,k);
count++;
if (count == k) {
res = root;
}
inOrder(root.right, k);
}
52、二叉树的深度
public int TreeDepth(TreeNode root) {
if (root == null) return 0;
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return Math.max(left, right) + 1;
}
53、判断是否为平衡二叉树
private boolean isBalance = true;
public boolean IsBalanced_Solution(TreeNode root) {
getHeight(root);
return isBalance;
}
private int getHeight(TreeNode root) {
if (root == null) return 0;
int left =getHeight(root.left);
int right = getHeight(root.right);
if (Math.abs(left - right) > 1) {
isBalance = false;
return -1;
}
return 1 + Math.max(left ,right);
}
54、数组中值出现一次的数字
55、和为S的两个数字
题目描述
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
int i = 0;
int j = array.length-1;
while(i < j){
int cur = array[i] + array[j];
if(cur == sum){
return new ArrayList<>(Arrays.asList(array[i],array[j]));
}
if(cur < sum){
i++;
}else{
j--;
}
}
return new ArrayList<>();
}
56、和为S的连续子序列
题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
解题思路
定义区间的左边界 left 区间的右边界right 然后不断滑动求该区间的和sum比对
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
int start = 1, end = 2, curSum = 3;
while (end < sum) {
if (curSum > sum) {
curSum -= start;
start++;
}else if (curSum < sum) {
end++;
curSum += end;
}else {
ArrayList<Integer> temp = new ArrayList<>();
for (int i = start; i <= end; i++) {
temp.add(i);
}
res.add(temp);
curSum -= start;
start++;
end++;
curSum += end;
}
}
return res;
}
57、反转单词顺序列
题目描述
Input:
“I am a student.”
Output:
“student. a am I”
解题思路
题目应该有一个隐含条件,就是不能用额外的空间。先旋转每个单词,再旋转整个字符串
public String ReverseSentence(String str) {
int n = str.length();
char[] chars = str.toCharArray();
int i = 0, j = 0;
while (j <= n) {
if (j == n || chars[j] == ' ') {
reverse(chars, i , j - 1);
i = j + 1;
}
j++;
}
reverse(chars, 0, n - 1);
return new String(chars);
}
private void reverse(char[] chars, int i, int j) {
while (i < j) {
swap(chars, i++, j--);
}
}
private void swap(char[] chars, int i, int j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
58 左旋转字符串
题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
解题思路
public String LeftRotateString(String str,int n) {
if (str == null || str.length() == 0 || n == 0) return str;
char[] arr = str.toCharArray();
reverse(arr,0,n - 1);
reverse(arr,n, arr.length - 1);
reverse(arr, 0 , arr.length - 1);
return new String(arr);
}
private void reverse(char[] arr, int left, int right) {
while (left < right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
59、 滑动窗口的最大值
题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
解题思路
public ArrayList<Integer> maxInWindows(int [] nums, int size){
ArrayList<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0 || size <= 0) return res;
for (int i = 0; i <= nums.length - size; i++) {
int curMax = nums[i];
for (int j = i;j < i + size; j++) {
curMax = Math.max(curMax, nums[j]);
}
res.add(curMax);
}
return res;
}
维护一个大小为size的大根堆,先初始化堆的大小为size,然后再从size出往后遍历,并逐步移除前size位上的数子
public ArrayList<Integer> maxInWindows(int [] nums, int size){
ArrayList<Integer> res = new ArrayList<>();
if (size > nums.length || size < 1) {
return res;
}
PriorityQueue<Integer> heap = new PriorityQueue<>((o1, o2) -> o2 - o1);
for(int i = 0; i < size; i++) { //行成窗口
heap.offer(nums[i]);
}
res.add(heap.peek());
for (int i = 0, j = i + size; j < nums.length; i++,j++) { //维护一个大小为size的大根堆
heap.remove(nums[i]);
heap.offer(nums[j]);
res.add(heap.peek());
}
return res;
}
维护一个大小为size的链表,链表从头部到尾部是从大到小排列的。
每次都要去判断队首元素的下标是否过期
public ArrayList<Integer> maxInWindows(int [] nums, int size){
ArrayList<Integer> res = new ArrayList<>();
if (size > nums.length || size < 1) {
return res;
}
LinkedList<Integer> queue = new LinkedList<>();
for (int i = 0; i < nums.length; i++) {
//队列从头到尾是从大到小的
while (!queue.isEmpty() && nums[queue.peekLast()] < nums[i]) {
queue.pollLast();
}
queue.addLast(i);
if (queue.peek() <= i - size) { //移除过期的元素
queue.poll();
}
if (i - size + 1 >= 0) { //行成窗口
res.add(nums[queue.peek()]);
}
}
return res;
}
60、扑克牌的顺子
题目描述
五张牌,其中大小鬼为癞子,牌面为 0。判断这五张牌是否能组成顺子。
解题思路
排序数组,并找到所有的0,再用0去补齐不连续的顺子
public boolean isContinuous(int [] nums) {
if (nums.length < 5) return false;
Arrays.sort(nums);
int count = 0;
for (int num : nums) {
if (num == 0) count++; //统计大小王的次数
}
//用癞子去补全不连续的顺子
for (int i = count; i < nums.length - 1; i++) {
if (nums[i + 1] == nums[i]) {
return false;
}
count -= nums[i + 1] - nums[i] - 1; // 1 0 0 5 0 5 - 1 = 3 需要三个癞子
}
return count >= 0;
}
61、圆圈中最后剩下的数(约瑟夫问题)
题目描述
让小朋友们围成一个大圈。然后,随机指定一个数 m,让编号为 0 的小朋友开始报数。每次喊到 m-1 的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续 0…m-1 报数 … 这样下去 … 直到剩下最后一个小朋友,可以不用表演。
解题思路
public int LastRemaining_Solution(int n, int m) {
if (n == 0) return -1;
if (n == 1) return 0;
return (LastRemaining_Solution(n - 1, m) + m ) % n;
}
用链表来模拟
public int LastRemaining_Solution(int n, int m) {
if (n == 0 || m == 0) return - 1;
LinkedList<Integer> list = new LinkedList<>();
for (int i = 0; i < n; i++) {
list.add(i);
}
int removeIndex = 0;
while (list.size() != 1) {
removeIndex = (removeIndex + m - 1) % list.size(); //防止溢出
list.remove(removeIndex);
}
return list.get(0);
}
62、买卖股票的最佳时期
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) return 0;
int n = prices.length;
int[][] dp = new int[n][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
dp[i][1] = Math.max(dp[i - 1][1], - prices[i]);
}
return dp[n - 1][0];
}
63、求 1+2+3+…+n
题目描述
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
public int Sum_Solution(int n) {
//等差数列
int sum = (int)(Math.pow(n, 2) + n);
return sum >> 1;
}
64、不用加减乘除做加法
5 : 0101
7 : 0111
5 ^ 7 = 0010 = 2
5 & 7 = 0101 0101 <<1 = 1010 = 10
public int Add(int a,int b) {
return b == 0 ? a : Add(a ^ b, (a & b) << 1);
}
65、构建乘积数组
题目描述
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…*A[i-1]A[i+1]…*A[n-1]。不能使用除法。(注意:规定B[0] = A[1] * A[2] * … * A[n-1],B[n-1] = A[0] * A[1] * … * A[n-2];)
解题思路
public int[] multiply(int[] A) {
int n = A.length;
int[] B = new int[n];
for (int i = 0, product = 1; i < n; product *= A[i], i++) /* 从左往右累乘 */
B[i] = product;
for (int i = n - 1, product = 1; i >= 0; product *= A[i], i--) /* 从右往左累乘 */
B[i] *= product;
return B;
}
66 把字符串转换成整数
public int StrToInt(String str) {
if (str == null || str.length() == 0)
return 0;
boolean isNegative = str.charAt(0) == '-';
int ret = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (i == 0 && (c == '+' || c == '-')) /* 符号判定 */
continue;
if (c < '0' || c > '9') /* 非法输入 */
return 0;
ret = ret * 10 + (c - '0');
}
return isNegative ? -ret : ret;
}
67 二叉树的最近公共祖先
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == root || q == root) {
return root; //3,5 3,1
}
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if (left != null && right != null) {
return root; //5,1
}else if (left != null && right == null) {
return left; //5,2 都在左子树的情况
}else if (left == null && right != null) {
return right; //1,0 都在右子树的情况
}
return null;
}