【问题标题】:How do I find the largest value smaller than or equal to X and the smallest value greater than or equal to X?如何找到小于或等于 X 的最大值和大于或等于 X 的最小值?
【发布时间】:2016-09-30 15:36:44
【问题描述】:

我正在尝试使用 C++ 中 algorithm 库中的 lower_boundupper_bound 函数来查找以下内容:

  • 最大值小于或等于到数字 X。
  • 最小值大于或等于到数字 X。

我写了以下代码:

#include <iostream>
#include <algorithm>

int main() {

    using namespace std;

    int numElems;
    cin >> numElems;

    int ar[numElems];
    for (int i = 0; i < numElems; ++i)
        cin >> ar[i];
    stable_sort(ar,ar+numElems);

    cout << "Input number X to find the largest number samller than or equal to X\n";
    int X;
    cin >> X;

    int *iter = lower_bound(ar,ar+numElems,X);
    if (iter == ar+numElems)
        cout << "Sorry, no such number exists\n";
    else if (*iter != X && iter != ar)
        cout << *(iter-1) << endl;
    else 
        cout << *iter << endl;

    cout << "Input number X to find the smallest number greater than or equal to X\n";
    cin >> X;

    int *iter2 = lower_bound(ar,ar+numElems,X);
    if (iter2 == ar+numElems)
        cout << "Sorry, no such number exists\n";
    else
        cout << *iter2 << endl;

    return 0;   
}

但对于一些随机测试用例,它给了我错误的答案。

谁能在我的程序中找到不正确的代码?

【问题讨论】:

  • 请提供一个输入序列,其中包含您得到的预期和实际结果。
  • 如果你有一个单元素数组,只要X 不是那个元素,你就会得到“小于”的错误结果。 (调试提示:从不可能出错的小而琐碎的测试用例开始。)

标签: c++ algorithm binary-search divide-and-conquer


【解决方案1】:

小于或等于数字 X 的最大值。

对我来说,排序数组最简单的方法是:

auto ret = upper_bound(arr.rbegin(), arr.rend(), X,
                       [](int a, int b){return a>=b;});

【讨论】:

    【解决方案2】:

    对于“小于或等于”情况,您的逻辑有点倒退。

    lower_bound 的结果需要考虑三种情况:它返回最后一个元素之后的位置、第一个元素的位置或两者之间的某个位置

    如果iter == ar+numElems,您要查找的值是数组的最后一个元素(因为所有元素都小于X)。

    如果iter == ar(第一个位置),有两种情况; *iter == X*iter != X.
    如果*iter == XX 是您的结果,因为数组中没有更小的值。
    如果*iter != X,则最小数组元素大于X,你没有结果。

    否则(即iter != ar)结果为ar[-1]

    【讨论】:

      【解决方案3】:

      让我告诉你你在哪里犯了一些错误:

      int array[] = { 10, 15, 18 };
      
      //Input number X to find the largest number samller than or equal to X
      
      //X = 16
      15 //Correct!
      
      //X = 200
      Sorry, no such number exists //Wrong! Should be 18
      
      //X = 1
      10 //Wrong! There is no such number
      
      //Input number X to find the smallest number greater than or equal to X
      
      //X = 16
      18 //Correct!
      
      //X = 200
      Sorry, no such number exists //Correct!
      
      //X = 1
      10 //Correct!
      

      如您所见,第一个测试用例是罪魁祸首,您错误地假设如果最后一个元素超过最后一个元素,则它没有找到该元素。但事实并非如此,因为最后一个元素总是是最小的! 你应该删除条件。

      接下来,对于第三个输入,你永远不会检查是否iter == ar,但你应该检查,因为iter == ar当找到第一个元素时,如果不是X,那么就没有这个数字(它不可能是前一个,因为iter已经是第一个了!

      【讨论】:

        猜你喜欢
        • 2017-03-14
        • 2018-08-09
        • 2013-09-02
        • 1970-01-01
        • 2019-09-26
        • 2011-01-25
        • 2021-06-09
        • 2022-01-19
        • 1970-01-01
        相关资源
        最近更新 更多