hackerrank上复健了Lower Bound-STL
这道题 开始没注意他说用low_bound()
, 然后就死磕了一番, 结果到后面就TLE了。(写的真的啰嗦不看也罢就是传统的按顺序遍历查询大了就break的那种哇塞这题还折腾了我好久老了老了
题目链接在这里:
Lower Bound-STL
(改用lower_bound()
就很顺利啊(代码跳过重点在后面
就 还是要懂一下这个template是怎么操作的 看看官网怎么说
function template
std::lower_bound
default (1)
template <class ForwardIterator, class T>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,
const T& val);
custom (2)
template <class ForwardIterator, class T, class Compare>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);
Return iterator to lower bound
Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.
The elements are compared using operator< for the first version, and comp for the second. The elements in the range shall already be sorted according to this same criterion (operator< or comp), or at least partitioned with respect to val.
The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted range, which is specially efficient for random-access iterators.
Unlike upper_bound, the value pointed by the iterator returned by this function may also be equivalent to val, and not only greater.
The behavior of this function template is equivalent to
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;
}
首先,要被查找的序列是有序的, 然后它返回的是一个不小于val
(也就是第三个参数)的第一个元素的迭代器。然后它是二分法进行查找(是吧?
std::advance
template <class InputIterator, class Distance>
void advance (InputIterator& it, Distance n);
Advance iterator:Advances the iterator it by n element positions. 经过一次advance,it
就移动到step的位置也就是二分处,此时it
的值就为first[step]
有两行代码稍微嘴一下(其实也没必要:
first=++it;
: it
先自增1, 再赋值给first
count-=step+1;
: count = count - (step+1);
啊先这样 看完iteration和templates相关后再来补充
等等 既然底层是二分查找 那我为什么之前还在死磕???????