【问题标题】:There is a given element say N. How to modify Binary Search to find greatest element in a sorted vector which smaller than N有一个给定的元素说 N。如何修改 Binary Search 以在小于 N 的排序向量中找到最大元素
【发布时间】:2021-06-05 09:54:22
【问题描述】:

例如: 让我们有一个带有元素的排序向量:[1, 3, 4, 6, 7, 10, 11, 13] 我们有一个元素N = 5

我想输出为:

4

因为 4 是小于 N 的最大元素。

我想修改二分搜索来得到答案

【问题讨论】:

标签: c++ vector binary-search c++-standard-library


【解决方案1】:

如果向量中有一个等于N 的元素,您希望发生什么?

我会使用std::lower_bound(或std::upper_bound,具体取决于上述问题的答案)。它以对数时间运行,这意味着它可能在后台使用二进制搜索。

std::optional<int> find_first_less_than(int n, std::vector<int> data) {
    // things must be sorted before processing
    std::sort(data.begin(), data.end());

    auto it = std::lower_bound(data.begin(), data.end(), n);

    // if all of the elements are above N, we'll return nullopt
    if (it == data.begin()) return std::nullopt;

    return *std::prev(it);
}

【讨论】:

  • 我将执行二分查找来检查向量中是否存在等于 N 的元素。
猜你喜欢
  • 2012-12-27
  • 2012-12-17
  • 2017-08-04
  • 1970-01-01
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
相关资源
最近更新 更多