zoukankan      html  css  js  c++  java
  • lintcode:线段树的查询

    线段树的查询

    对于一个有n个数的整数数组,在对应的线段树中, 根节点所代表的区间为0-n-1, 每个节点有一个额外的属性max,值为该节点所代表的数组区间start到end内的最大值。

    为SegmentTree设计一个 query 的方法,接受3个参数rootstartend,线段树root所代表的数组中子区间[start, end]内的最大值。

    解题

    递归

    /**
     * Definition of SegmentTreeNode:
     * public class SegmentTreeNode {
     *     public int start, end, max;
     *     public SegmentTreeNode left, right;
     *     public SegmentTreeNode(int start, int end, int max) {
     *         this.start = start;
     *         this.end = end;
     *         this.max = max
     *         this.left = this.right = null;
     *     }
     * }
     */
    public class Solution {
        /**
         *@param root, start, end: The root of segment tree and 
         *                         an segment / interval
         *@return: The maximum number in the interval [start, end]
         */
        public int query(SegmentTreeNode root, int start, int end) {
            // write your code here
            if(null == root) return Integer.MIN_VALUE;
            if(root.start > end || root.end < start || start > end) return Integer.MIN_VALUE;
            if(root.start >= start && root.end <= end) return root.max;
    
            int mid = root.start + (root.end - root.start)/2;
            int leftmax = query(root.left, start, Math.min(mid, end));
            int rightmax = query(root.right, Math.max(mid, start), end);
            return Math.max(leftmax, rightmax);
        }
    }
    Java Code
  • 相关阅读:
    华东交通大学2017年ACM双基程序设计大赛题解
    hdu2010(dfs+剪枝)
    欧拉函数phic以及超大数的快速幂
    想了一天的题目QAQ 毛线数列的最值
    记一下STL的一个题
    hdu1877进制转换
    hdu1002大数相加
    hdu1576逆元的一道水题
    Courses
    CodeForce-813B The Golden Age(数学+枚举)
  • 原文地址:https://www.cnblogs.com/bbbblog/p/5284821.html
Copyright © 2011-2022 走看看