剑指offer 2021/8/4

43 篇文章 0 订阅
27 篇文章 0 订阅

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值