求二叉树的最大深度, 基本思路如下: 设定一个全局变量记录二叉树的深度,利用递归,没遍历一层都将临时深度变量+1,并在每一节点递归结束后判断深度大小. 具体代码如下: package algorithm; import basic.TreeNode; public class MaxDepthOfTree { private int depth = 0; public int maxDepth(TreeNode root) { acquireDepth(root,0); return depth…
在二进制中,2的幂的数字用二进制表示时只会有一位表示为1,其余都为0,基于这个前提,可以有两种方案: 1. 做位移操作 2. 与数值取反并与原数值做与操作,判断是否与原来的数值相同 对于方案1,我的想法是对数值 n 先做一次右移的移位操作,然后在对右移后的数做左移操作,判断两次操作前后的数值是否相同,以下是代码: public boolean isPowerOfTwo(int n) { for(int i=0;i<32;i++){ int temp = n >> i; int large…
事先说明,如果不是评论区的大牛一语点破,我可能还会陷在死胡同里出不来,这道题其实很简单,利用了任何一个学过二进制的人都了解的定理,即: 1. 异或操作满足交换律 : a ^ b ^ c 等价于 a ^ c ^ b 2. 0与任何数的异或都是数字本身: 0 ^ n = n 3. 相同的两个数的异或结果为0: a ^ a =0 基于以上三个定理,病结合数组中相同元素只会出现两次的前提,就可以得出,初始时设一个变量为0,记录异或结果,遍历数组,不断的执行异或,最终结果就是只出现一次的元素 public…
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum e…
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum e…
LeetCode相关的网上资源比较多,看到题目一定要自己做一遍,然后去学习参考其他的解法. 链接: https://oj.leetcode.com/problems/min-stack/ 题目描述: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Remov…
LeetCode 155:最小栈 Min Stack 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈. push(x) -- 将元素 x 推入栈中. pop() -- 删除栈顶的元素. top() -- 获取栈顶元素. getMin() -- 检索栈中的最小元素. Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu…
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum e…
题目 232.用栈实现队列 class MyQueue { private Stack<Integer> in = new Stack<>(); private Stack<Integer> out = new Stack<>(); public void push(int x) { in.push(x); } public int pop() { in2out(); return out.pop(); } public int peek() { in2ou…