lintcode-区间最小数-205

class SegmentTreeNode {
    public int start, end, min;
    public SegmentTreeNode left, right;
    public SegmentTreeNode(int start, int end) {
          this.start = start;
          this.end = end;
          this.min = 0;
          this.left = this.right = null;
    }
}
public class Solution {
    
    public SegmentTreeNode build(int start, int end, int[] A) {
        
        if(start > end) {  
            return null;
        }
        
        SegmentTreeNode root = new SegmentTreeNode(start, end);
        
        if(start != end) {
            int mid = (start + end) / 2;
            root.left = build(start, mid, A);
            root.right = build(mid+1, end, A);
            root.min = Math.min(root.left.min, root.right.min);
        } else {
            root.min = A[start];
        }
        return root;
    }
    public int query(SegmentTreeNode root, int start, int end) {
      
        if(start <= root.start && root.end <= end) {
            return root.min;
        }
    
        int mid = (root.start + root.end)/2;
        
        if(start>mid) 
            return query(root.right,start,end);
        
        else if(mid+1>end)  
            return query(root.left, start, end);
        
        else
            return Math.min(query(root.left,start,mid),query(root.right,mid+1,end));
    }
    
    public ArrayList<Integer> intervalMinNumber(int[] A, 
                                                ArrayList<Interval> queries) {
        SegmentTreeNode root = build(0, A.length - 1, A);
        ArrayList ans = new ArrayList<Integer>();
        for(Interval in : queries) {
            ans.add(query(root, in.start, in.end));
        }
        return ans;
    }
}

你可能感兴趣的:(lintcode-区间最小数-205)