1. Introduction to Discretization:
In some algorithm problems, the numerical range will be very large, such as 0 ~ 1 0 9 10^9109 , but the number is relatively small, for example, only1 0 5 10^5105 , but in our program, these values need to be used as subscripts, and it depends on the order relationship between these values. It doesn't really matter how much it is, open a1 0 9 10^910The array of 9 is obviously unwise, because at most there is only1 0 5 10^5105 data, then no matter how big the value is, we can uniquely map these numbers to 0 ~1 0 5 10^510Among 5 , we only need to open1 0 5 10^510The array of 5 is enough, and the process of mapping is discretization.
2. Steps:
(1)去重
(2)二分查找映射的数
3. Code template:
(1) De-duplication
vector<int>alls;//假设vector中存了需要离散化的所有数据
sort(alls.begin(),alls.end());
alls.erase(unique(alls.begin(),alls.end()),alls.end());
( unique function )
(2) Binary search
int find(int x)
{
int l=0;r=alls.size()-1;
while(l<r)
{
int mid=l+r>>1;
if(alls[mid]>=x)r=mid;
else l=mid+1;
}
return r;//return r+1表示映射以1开始
}
--A certain scientific super-electromagnetic gun