一刷的思路应该是错的
正确的做法是每次不改变传入的start和end
对每次的range分Partial Overlap, Total Overlap和No Overlap三种情况讨论
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
int left = root.start;
int right = root.end;
//1.No Overlap
if (root == null || start > end || end < left || start > right) return Integer.MIN_VALUE;
//2.Total Overlap
if (start <= left && end >= right) return root.max;
//3.Partial Overlap
return Math.max(query(root.left, start, end), query(root.right, start, end));
}
}
一刷
写了一个bug
int mid = (root.start + root.end) / 2; 此处mid应该是树Node的mid
而不应该是query的mid
Time O(logn)
* 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 (start > end) throw new IllegalArgumentException();
if (root.start == start && root.end == end) return root.max;
int mid = (root.start + root.end) / 2;
if (end <= mid) return query(root.left, start, end);
else if (start > mid) return query(root.right, start, end);
else return Math.max(query(root.left, start, mid), query(root.right, mid + 1, end));
}
}
No comments:
Post a Comment