*[Lintcode]Interval Minimum Number 区间最小数

Given an integer array (index from 0 to n-1, where n is the size of this array), and an query list. Each query has two integers [start, end]. For each query, calculate the minimum number between index start and end in the given array, return the result list.


Example

For array [1,2,7,8,5], and queries [(1,2),(0,4),(2,4)], return [2,1,5]

用线段树直接求解即可。 

/**
 * Definition of Interval:
 * public classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this.start = start;
 *         this.end = end;
 *     }
 */
public class Solution {
    /**
     *@param A, queries: Given an integer array and an query list
     *@return: The result list
     */
    public ArrayList<Integer> intervalMinNumber(int[] A, 
                                                ArrayList<Interval> queries) {
        SegmentTreeNode s = build(A, 0, A.length - 1);
        ArrayList<Integer> res = new ArrayList<Integer>();
        for(int i = 0; i < queries.size(); i++) {
            Interval interval = queries.get(i);
            res.add(find(s, interval));
        }
        return res;
    }
    
    private int find(SegmentTreeNode s, Interval i) {
        if(s == null) return Integer.MAX_VALUE;
        if(i.start > s.end || i.end < s.start) return Integer.MAX_VALUE;

        if(i.start <= s.start && i.end >= s.end) return s.min;
        else {
            int left = find(s.left, i);
            int right = find(s.right, i);
            return Math.min(left, right);
        }
    }
    
    private SegmentTreeNode build(int[] A, int start, int end) {
        if(start > end) return null;
        
        SegmentTreeNode root = new SegmentTreeNode(start, end);
        if(start == end) {
            root.min = A[start];
            return root;
        }
        
        root.left = build(A, start, (start + end) / 2);
        root.right = build(A, (start + end) / 2 + 1, end);
        
        root.min = Math.min(root.left.min, root.right.min);
        return root;
    }
    
    class SegmentTreeNode {
        public int start, end, min;
        public SegmentTreeNode left, right;
        public SegmentTreeNode(int start, int end) {
          this.start = start;
          this.end = end;
          this.left = this.right = null;
      }
  }
 
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值