sweet1cris

Untitled

Jan 10th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1. /**
  2.  * Definition of SegmentTreeNode:
  3.  * public class SegmentTreeNode {
  4.  *     public int start, end, max;
  5.  *     public SegmentTreeNode left, right;
  6.  *     public SegmentTreeNode(int start, int end, int max) {
  7.  *         this.start = start;
  8.  *         this.end = end;
  9.  *         this.max = max
  10.  *         this.left = this.right = null;
  11.  *     }
  12.  * }
  13.  */
  14. public class Solution {
  15.     /**
  16.      *@param root, start, end: The root of segment tree and
  17.      *                         an segment / interval
  18.      *@return: The maximum number in the interval [start, end]
  19.      */
  20.     public int query(SegmentTreeNode root, int start, int end) {
  21.         // write your code here
  22.         if(start == root.start && root.end == end) { // 相等
  23.             return root.max;
  24.         }
  25.        
  26.        
  27.         int mid = (root.start + root.end)/2;
  28.         int leftmax = Integer.MIN_VALUE, rightmax = Integer.MIN_VALUE;
  29.         // 左子区
  30.         if(start <= mid) {
  31.             if( mid < end) { // 分裂
  32.                 leftmax =  query(root.left, start, mid);
  33.             } else { // 包含
  34.                 leftmax = query(root.left, start, end);
  35.             }
  36.             // leftmax = query(root.left, start, Math.min(mid,end));
  37.         }
  38.         // 右子区
  39.         if(mid < end) { // 分裂 3
  40.             if(start <= mid) {
  41.                 rightmax = query(root.right, mid+1, end);
  42.             } else { //  包含
  43.                 rightmax = query(root.right, start, end);
  44.             }
  45.             //rightmax = query(root.right, Math.max(mid+1,start), end);
  46.         }  
  47.         // else 就是不相交
  48.         return Math.max(leftmax, rightmax);
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment