59 - II. 队列的最大值
代码:
维护一个双端递减序列,有新元素加入时,将队列中比该元素小的元素出队。原队列执行出队操作时,若出队的元素与双端队列中元素相等,则同时执行出队操作。
class MaxQueue {
LinkedList<Integer> queue;
//维护一个递减序列
LinkedList<Integer> max;
public MaxQueue() {
queue = new LinkedList<>();
max = new LinkedList<>();
}
public int max_value() {
if(max.size()==0) return -1;
return max.getFirst();
}
public void push_back(int value) {
queue.add(value);
//将max中小于value的元素全部出队
while(max.size()!=0 && max.getLast()<value){
max.removeLast();
}
max.add(value);
}
public int pop_front() {
if(queue.size()==0)
return -1;
//Integer类型不能用==进行比较
if(queue.getFirst().equals(max.getFirst())){
max.pop();
}
return queue.pop();
}
}
/**
* Your MaxQueue object will be instantiated and called as such:
* MaxQueue obj = new MaxQueue();
* int param_1 = obj.max_value();
* obj.push_back(value);
* int param_3 = obj.pop_front();
*/
54. 二叉搜索树的第k大节点
代码:
以右子树->根节点->左子树的顺序遍历二叉树。当遍历到第k个节点时返回。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int k;
int res;
public int kthLargest(TreeNode root, int k) {
this.k = k;
/*if(root==null)
return 0;*/
return dfs(root);
}
int dfs(TreeNode root){
if(root.right != null){
dfs(root.right);
}
if(--k==0) res = root.val;
if(root.left != null){
dfs(root.left);
}
return res;
}
}
改进:
可以添加一句
if(k==0) return res;
进行剪枝。
15. 二进制中1的个数
法一:
逐位判断
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res=0;
while(n!=0){
res+=n&1;
n >>>= 1;
}
return res;
}
}
法二:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res=0;
while(n!=0){
res++;
//此操作相当于将n最右边的1变为0
n&=n-1;
}
return res;
}
}