剑指offer day3
22 、链表中倒数第k个节点 https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
剑指offer中对这道题有一个隐蔽性的判断条件,即我们需要判断k是否大于0且小于链表的长度,这就意味着我们一定要遍历一遍链表,然后获得整个链表的长度。leetcode相对于更加弱化了一点,在这里我们直接利用快慢指针即可
1 | class Solution { |
24、反转链表 https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
递归
1
2
3
4
5
6
7
8
9class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode newNode=reverseList(head.next);
head.next.next=head;
head.next=null;
return newNode;
}
}非递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
//创建一个新的头节点,遍历整个链表, 然后将其挂接
ListNode newNode=null;
ListNode cur=head;
while(cur!=null){
ListNode temp=cur.next;
cur.next=newNode;
newNode=cur;
cur=temp;
}
return newNode;
}
}
25、合并两个排序的链表 https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
该题类似于归并排序的最后一个步骤,merge两个排好序的数组,这里也用一样的思路来进行
- 非递归
1 | class Solution { |
- 递归
1 | class Solution { |
26、树的子结构 https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/
经典双递归
1 | class Solution { |
27、二叉树的镜像 https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/
非递归-BFS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root==null) return null;
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int n=queue.size();
for(int i=0;i<n;i++){
//在层序遍历的时候直接对左右两个节点进行交换
TreeNode cur=queue.poll();
TreeNode temp=cur.left;
cur.left=cur.right;
cur.right=temp;
if(cur.left!=null) queue.add(cur.left);
if(cur.right!=null) queue.add(cur.right);
}
}
return root;
}
}
递归
1
2
3
4
5
6
7
8
9class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root==null) return null;
TreeNode left=root.left;
root.left=mirrorTree(root.right);
root.right=mirrorTree(left);
return root;
}
}
28、对称的二叉树 https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/
递归判断
1 | class Solution { |
29、顺时针打印矩阵 https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/
经典搜索模拟题,碰到边界掉转方向
1 | class Solution { |
30、包含min函数的栈 https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/submissions/
利用两个栈实现最小栈,辅助栈为单调栈
1 | class MinStack { |
31、栈的压入、弹出序列 https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/
用栈去模拟该过程
1 | class Solution{ |
32-1、从上到下打印二叉树 https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/
BFS
1 | class Solution{ |