只是轉儲所有的值,開始和結束到一個向量或數組,然後對其進行排序。因爲範圍不重疊,所以一旦數組被排序,就會有開始,停止,開始,停止等等。然後,可以使用二進制搜索來查找向量的索引。那麼它只是一個問題,即是否它的奇數或偶數
假設,你是從流
vector<int> ranges;
int n;
while(in >> n){
ranges.push_back(n);
}
sort(ranges.begin(),ranges.end())
int x;
cout <<"please enter a value to search for: ";
cin >> x;
int index = binary_search(x,ranges);
if(index % 2){
cout << "The value " << x << "is in the range of "
<< ranges[index-1] << " to " << ranges[index] << endl;
}else{
if(ranges[index] == x){
cout << "The value " << x << "is in the range of "
<< ranges[index] << " to " << ranges[index+1] << endl;
}
else{
cout << "Value " << x << " is not in any range\n";
}
}
其中二進制搜索將被定義爲
int binary_search(int x, vector<int>& vec, int s = 0; int f = -1){
if(f == -1)f=vec.size();
if(s >= f) return s;
int n = (f-s)/2 + s;
if(vec[n] == x)return n;
if(vec[n] < x)return binary_search(x,vec,s,n-1);
return binary_search(x,vec,n+1,f);
}
越來越範圍但願我沒有」 t搞砸了二分查找,但它的設計方式是,如果找不到該值,則返回下一個最大值的索引。
你的範圍重疊嗎?查找任何特定數字的範圍是否會產生唯一的答案? – ravenspoint 2011-12-14 21:28:05
範圍可以重疊嗎? – 2011-12-14 21:28:25
你會有多少個範圍?他們多久更換一次?總人口數值有多大(即最大值 - 最小值)? – 2011-12-14 21:32:46