若一些数据本身很大,无法作为下标储存,且数据的作用只和其相对大小有关时,可以将数据进行离散化。
举例说明:
12345 < 123456 < 1234567
离散化后变成 : 1 < 2 < 3
代码:
// B为A的副本。
sort(B,B+n);
int size = unqiue(B,B+n) - B; //size为离散化后元素的个数。
for(int i=0;i<n;i++)
A[i] = lower_bound(B,B+size,A[i]) - B + 1; // 离散化
unique 实现:
template <class ForwardIterator>
ForwardIterator unique (ForwardIterator first, ForwardIterator last)
{
if (first==last) return last;
ForwardIterator result = first;
while (++first != last)
{
if (!(*result == *first)) // or: if (!pred(*result,*first)) for version (2)
*(++result)=*first;
}
return ++result;
}
可以看到最后返回的是去掉所用相同元素后最后一位的后面的地址.
Removes all but the first element from every consecutive group of equivalent elements in the range
[first,last)
.
lower_bound实现:
template <class ForwardIterator, class T>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val)
{
ForwardIterator it;
iterator_traits<ForwardIterator>::difference_type count, step;
count = distance(first,last);
while (count>0)
{
it = first; step=count/2; advance (it,step);
if (*it<val) { // or: if (comp(*it,val)), for version (2)
first=++it;
count-=step+1;
}
else count=step;
}
return first;
}
Returns an iterator pointing to the first element in the range
[first,last)
which does not compare less than
val.