题目主要来源:LeetCode。主要选自剑指offer、程序员面试宝典。
每日尽可能保持 N+1 道题,N 取 0 到 9。部分解法是从LeetCode上大佬们的解法中拿过来的,如有侵权,告知立删
文章目录
- 0x01 [剑指 Offer 41. 数据流中的中位数](https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/)
- 0x02 [剑指 Offer 36. 二叉搜索树与双向链表](https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/)
- 0x03 [剑指 Offer 31. 栈的压入、弹出序列](https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/)
0x01 剑指 Offer 41. 数据流中的中位数
/**
* JZ41 大顶堆+小顶堆
*
* @author Anjude
* @date 2021/7/18 12:25
*/
public class JZ41 {
Queue<Integer> A, B;
public JZ41() {
A = new PriorityQueue<>(); // 小顶堆,保存较大的一半
B = new PriorityQueue<>((x, y) -> (y - x)); // 大顶堆,保存较小的一半
}
public void addNum(int num) {
if (A.size() != B.size()) {
A.add(num);
B.add(A.poll());
} else {
B.add(num);
A.add(B.poll());
}
}
public double findMedian() {
return A.size() != B.size() ? A.peek() : (A.peek() + B.peek()) / 2.0;
}
}
0x02 剑指 Offer 36. 二叉搜索树与双向链表
/**
* JZ36 中序遍历
*
* @author Anjude
* @date 2021/7/18 17:13
*/
public class JZ36 {
Node pre, head;
public Node treeToDoublyList(Node root) {
if (root == null) return null;
dfs(root);
head.left = pre;
pre.right = head;
return head;
}
private void dfs(Node root) {
if (root == null) return;
dfs(root.left);
if (pre != null) pre.right = root;
else head = root;
root.left = pre;
pre = root;
dfs(root.right);
}
class Node {
public int val;
public Node left;
public Node right;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right) {
val = _val;
left = _left;
right = _right;
}
}
}
0x03 剑指 Offer 31. 栈的压入、弹出序列
/**
* JZ31 模拟出栈
*
* @author Anjude
* @date 2021/7/18 19:09
*/
public class JZ31 {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<>();
int i = 0;
int len = popped.length;
for (int num : pushed) {
stack.push(num);
while (stack.size() != 0 && i < len && stack.peek() == popped[i]) {
stack.pop();
i++;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
JZ31 jz31 = new JZ31();
jz31.validateStackSequences(new int[]{1, 0}, new int[]{1, 0});
}
}