标签:
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.
For array [1,2,7,8,5]
, and queries [(1,2),(0,4),(2,4)]
, return [2,1,5]
Analysis:
Use Segment tree to maintain the minimun value from index i to j.
1 /** 2 * Definition of Interval: 3 * public classs Interval { 4 * int start, end; 5 * Interval(int start, int end) { 6 * this.start = start; 7 * this.end = end; 8 * } 9 */ 10 public class Solution { 11 /** 12 *@param A, queries: Given an integer array and an query list 13 *@return: The result list 14 */ 15 SegmentTreeNode root; 16 17 public ArrayList<Integer> intervalMinNumber(int[] A, 18 ArrayList<Interval> queries) { 19 // write your code here 20 ArrayList<Integer> res = new ArrayList<Integer>(); 21 root = buildTree(A, 0, A.length-1); 22 query(res, queries); 23 return res; 24 } 25 26 public void query(ArrayList<Integer> res, ArrayList<Interval> queries) { 27 for (Interval interval : queries) { 28 int result = queryTree(root, interval.start, interval.end); 29 res.add(result); 30 } 31 } 32 33 public int queryTree(SegmentTreeNode cur, int start, int end) { 34 if (start==cur.start && end==cur.end) { 35 return cur.min; 36 } 37 int mid = (cur.start + cur.end)/2; 38 if (end <= mid) return queryTree(cur.left, start, end); 39 else if (start > mid) return queryTree(cur.right, start, end); 40 else return Math.min(queryTree(cur.left, start, mid), queryTree(cur.right, mid+1, end)); 41 } 42 43 public SegmentTreeNode buildTree(int[] A, int start, int end) { 44 SegmentTreeNode cur = new SegmentTreeNode(start, end); 45 if (start == end) { 46 cur.min = A[start]; 47 } 48 else { 49 int mid = (start+end)/2; 50 cur.left = buildTree(A, start, mid); 51 cur.right = buildTree(A, mid+1, end); 52 cur.min = Math.min(cur.left.min, cur.right.min); 53 } 54 return cur; 55 } 56 } 57 58 class SegmentTreeNode { 59 int min; 60 int start; 61 int end; 62 SegmentTreeNode left; 63 SegmentTreeNode right; 64 public SegmentTreeNode(int start, int end) { 65 this.start = start; 66 this.end = end; 67 this.min = Integer.MAX_VALUE; 68 this.left = null; 69 this.right = null; 70 } 71 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5671836.html