链接:https://www.lintcode.com/zh-cn/problem/interval-minimum-number/
样例
对于数组 [1,2,7,8,5]
, 查询 [(1,2),(0,4),(2,4)]
,返回 [2,1,5]
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
* }
*/
class Solution {
public:
/**
* @param A: An integer array
* @param queries: An query list
* @return: The result list
*/
vector<int> intervalMinNumber(vector<int> &A, vector<Interval> &queries) {
// write your code here
if(A.empty() || quries.empty()) return vector<int>();
vector<int> result;
SegmentTreeNode* root=build(0,A.size()-1,A);
for(int i=0;i<queries.size();i++)
{
result.push_back(query(root,queries[i].start,queries[i].end));
}
return result;
}
SegmentTreeNode* build(int start,int end,vector<int>& nums)
{
if(start>end) return NULL;
SegmentTreeNode* root=new SegmentTreeNode(start,end,0);
if(start!=end)
{
root->left=build(start,start+(end-start)/2,nums);
root->right=build(start+(end-start)/2+1,end,nums);
root->max=min(root->left->max,root->right->max);
}
else
{
root->max=nums[start];
}
return root;
}
int query(SegmentTreeNode* root,int start,int end)
{
int mid=root->start+(root->end-root->start)/2;
if(start<=root->start && end>=root->end) return root->max;
else if(mid<start) return query(root->right,start,end);
else if(mid+1>end) return query(root->left,start,end);
else return min(query(root->left,start,mid),query(root->right,mid+1,end));
}
};