离散化

若一些数据本身很大,无法作为下标储存,且数据的作用只和其相对大小有关时,可以将数据进行离散化。
举例说明:
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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值