gpt4 book ai didi

C++二进制搜索以查找不动点的索引

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:01:51 28 4
gpt4 key购买 nike

我正在实现一个函数,用于查找 A[i] = i 处的不动点。

size_t find_fixed_point(const vector<int>& list)
{
auto lower = list.begin();
auto upper = list.end() - 1;

while (lower < upper)
{
auto mid = lower + (upper-lower)/2;

if ( *mid <= (mid - list.begin()) )
{
// keep searching on left side
upper = mid;
}
else
{
// keep searching on right side
lower = mid + 1;
}
}

return lower - list.begin();
}

所以如果我将其应用于以下 vector

    vector<int> numbers = {-10, -5, 1, 3, 13, 13, 50, 70};

auto temp = find_fixed_point(numbers);
cout << numbers[temp];

它应该给出 3 作为固定点,但只给出 -10 是行不通的。

该算法看起来不错,但它不起作用。有人有想法吗?谢谢,

最佳答案

我认为您的比较运算符用错了方式:

size_t find_fixed_point(const vector<int>& list)
{
auto lower = list.begin();
auto upper = list.end() - 1;

while (lower < upper)
{
auto mid = lower + (upper-lower)/2;

if ( *mid >= (mid - list.begin()) )
{
// keep searching on left side
upper = mid;
}
else
{
// keep searching on right side
lower = mid + 1;
}
}

return lower - list.begin();
}

关于C++二进制搜索以查找不动点的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18416855/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com