📜  无界二分搜索示例(找到单调递增函数第一次变为正的点)

📅  最后修改于: 2021-09-16 11:05:31             🧑  作者: Mango

给定一个函数’int f(unsigned int x)’,它接受一个非负整数‘x’ 作为输入并返回一个整数作为输出。该函数相对于 x 的值单调递增,即对于每个输入 x,f(x+1) 的值大于 f(x)。找到 f() 首次变为正数的值 ‘n’。由于 f() 是单调递增的,因此 f(n+1), f(n+2),… 的值必须为正,而 f(n-2), f(n-3), … 的值必须为负。
在 O(logn) 时间内找到 n,您可以假设 f(x) 可以在 O(1) 时间内对任何输入 x 求值。

一个简单的解决方案是从 i 等于 0 开始,逐一计算 f(i) 对 1、2、3、4 等的值,直到找到正 f(i)。这有效,但需要 O(n) 时间。
我们可以应用二分搜索在 O(Logn) 时间内找到 n 吗?我们不能直接应用二分搜索,因为我们没有上限或高索引。这个想法是重复加倍直到我们找到一个正值,即检查 f() 的值是否为以下值,直到 f(i) 变为正值。

f(0) 
  f(1)
  f(2)
  f(4)
  f(8)
  f(16)
  f(32)
  ....
  ....
  f(high)
Let 'high' be the value of i when f() becomes positive for first time.

我们可以在找到“高”后应用二分搜索来找到 n 吗?我们现在可以应用二分搜索,我们可以在二分搜索中使用 ‘high/2’ 作为低索引和 ‘high’ 作为高索引。结果 n 必须介于 ‘high/2’ 和 ‘high’ 之间。
找到“高”的步骤数是 O(Logn)。所以我们可以在 O(Logn) 时间内找到“高”。二进制搜索在 high/2 和 high 之间花费的时间如何? ‘high’ 的值必须小于 2*n。 high/2 和 high 之间的元素数量必须是 O(n)。因此,二分查找的时间复杂度为O(Logn),整体时间复杂度为2*O(Logn),即O(Logn)。

C++
// C++ code for binary search
#include
using namespace std;
 
int binarySearch(int low, int high); // prototype
 
// Let's take an example function
// as f(x) = x^2 - 10*x - 20 Note that
// f(x) can be any monotonocally increasing function
int f(int x) { return (x*x - 10*x - 20); }
 
// Returns the value x where above
// function f() becomes positive
// first time.
int findFirstPositive()
{
    // When first value itself is positive
    if (f(0) > 0)
        return 0;
 
    // Find 'high' for binary search by repeated doubling
    int i = 1;
    while (f(i) <= 0)
        i = i*2;
 
    // Call binary search
    return binarySearch(i/2, i);
}
 
// Searches first positive value
// of f(i) where low <= i <= high
int binarySearch(int low, int high)
{
    if (high >= low)
    {
        int mid = low + (high - low)/2; /* mid = (low + high)/2 */
 
        // If f(mid) is greater than 0 and
        // one of the following two
        // conditions is true:
        // a) mid is equal to low
        // b) f(mid-1) is negative
        if (f(mid) > 0 && (mid == low || f(mid-1) <= 0))
            return mid;
 
        // If f(mid) is smaller than or equal to 0
        if (f(mid) <= 0)
            return binarySearch((mid + 1), high);
        else // f(mid) > 0
            return binarySearch(low, (mid -1));
    }
 
    /* Return -1 if there is no
    positive value in given range */
    return -1;
}
 
/* Driver code */
int main()
{
    cout<<"The value n where f() becomes" <<
        "positive first is "<< findFirstPositive();
    return 0;
}
 
// This code is contributed by rathbhupendra


C
#include 
int binarySearch(int low, int high); // prototype
 
// Let's take an example function as f(x) = x^2 - 10*x - 20
// Note that f(x) can be any monotonocally increasing function
int f(int x) { return (x*x - 10*x - 20); }
 
// Returns the value x where above function f() becomes positive
// first time.
int findFirstPositive()
{
    // When first value itself is positive
    if (f(0) > 0)
        return 0;
 
    // Find 'high' for binary search by repeated doubling
    int i = 1;
    while (f(i) <= 0)
        i = i*2;
 
    //  Call binary search
    return binarySearch(i/2, i);
}
 
// Searches first positive value of f(i) where low <= i <= high
int binarySearch(int low, int high)
{
    if (high >= low)
    {
        int mid = low + (high - low)/2; /* mid = (low + high)/2 */
 
        // If f(mid) is greater than 0 and one of the following two
        // conditions is true:
        // a) mid is equal to low
        // b) f(mid-1) is negative
        if (f(mid) > 0 && (mid == low || f(mid-1) <= 0))
            return mid;
 
        // If f(mid) is smaller than or equal to 0
        if (f(mid) <= 0)
            return binarySearch((mid + 1), high);
        else // f(mid) > 0
            return binarySearch(low, (mid -1));
    }
 
    /* Return -1 if there is no positive value in given range */
    return -1;
}
 
/* Driver program to check above functions */
int main()
{
    printf("The value n where f() becomes positive first is %d",
           findFirstPositive());
    return 0;
}


Java
// Java program for Binary Search
import java.util.*;
 
class Binary
{
    public static int f(int x)
    { return (x*x - 10*x - 20); }
 
    // Returns the value x where above
    // function f() becomes positive
    // first time.
    public static int findFirstPositive()
    {
        // When first value itself is positive
        if (f(0) > 0)
            return 0;
 
        // Find 'high' for binary search
        // by repeated doubling
        int i = 1;
        while (f(i) <= 0)
            i = i * 2;
 
        // Call binary search
        return binarySearch(i / 2, i);
    }
 
    // Searches first positive value of
    // f(i) where low <= i <= high
    public static int binarySearch(int low, int high)
    {
        if (high >= low)
        {  
            /* mid = (low + high)/2 */
            int mid = low + (high - low)/2;
 
            // If f(mid) is greater than 0 and
            // one of the following two
            // conditions is true:
            // a) mid is equal to low
            // b) f(mid-1) is negative
            if (f(mid) > 0 && (mid == low || f(mid-1) <= 0))
                return mid;
 
            // If f(mid) is smaller than or equal to 0
            if (f(mid) <= 0)
                return binarySearch((mid + 1), high);
            else // f(mid) > 0
                return binarySearch(low, (mid -1));
        }
 
        /* Return -1 if there is no positive
        value in given range */
        return -1;
    }
     
    // driver code
    public static void main(String[] args)
    {
        System.out.print ("The value n where f() "+
                         "becomes positive first is "+
                         findFirstPositive());
    }
}
 
// This code is contributed by rishabh_jain


Python3
# Python3 program for Unbound Binary search.
 
# Let's take an example function as
# f(x) = x^2 - 10*x - 20
# Note that f(x) can be any monotonocally
# increasing function
def f(x):
    return (x * x - 10 * x - 20)
 
# Returns the value x where above function
# f() becomes positive first time.
def findFirstPositive() :
     
    # When first value itself is positive
    if (f(0) > 0):
        return 0
 
    # Find 'high' for binary search
    # by repeated doubling
    i = 1
    while (f(i) <= 0) :
        i = i * 2
 
    # Call binary search
    return binarySearch(i/2, i)
 
# Searches first positive value of
# f(i) where low <= i <= high
def binarySearch(low, high):
    if (high >= low) :
         
        # mid = (low + high)/2
        mid = low + (high - low)/2; 
 
        # If f(mid) is greater than 0
        # and one of the following two
        # conditions is true:
        # a) mid is equal to low
        # b) f(mid-1) is negative
        if (f(mid) > 0 and (mid == low or f(mid-1) <= 0)) :
            return mid;
 
        # If f(mid) is smaller than or equal to 0
        if (f(mid) <= 0) :
            return binarySearch((mid + 1), high)
        else : # f(mid) > 0
            return binarySearch(low, (mid -1))
     
    # Return -1 if there is no positive
    # value in given range
    return -1;
 
# Driver Code
print ("The value n where f() becomes "+
      "positive first is ", findFirstPositive());
 
# This code is contributed by rishabh_jain


C#
// C# program for Binary Search
using System;
 
class Binary
{
    public static int f(int x)
    {
        return (x*x - 10*x - 20);
    }
 
    // Returns the value x where above
    // function f() becomes positive
    // first time.
    public static int findFirstPositive()
    {
        // When first value itself is positive
        if (f(0) > 0)
            return 0;
 
        // Find 'high' for binary search
        // by repeated doubling
        int i = 1;
        while (f(i) <= 0)
            i = i * 2;
 
        // Call binary search
        return binarySearch(i / 2, i);
    }
 
    // Searches first positive value of
    // f(i) where low <= i <= high
    public static int binarySearch(int low, int high)
    {
        if (high >= low)
        {
            /* mid = (low + high)/2 */
            int mid = low + (high - low)/2;
 
            // If f(mid) is greater than 0 and
            // one of the following two
            // conditions is true:
            // a) mid is equal to low
            // b) f(mid-1) is negative
            if (f(mid) > 0 && (mid == low ||
                             f(mid-1) <= 0))
                return mid;
 
            // If f(mid) is smaller than or equal to 0
            if (f(mid) <= 0)
                return binarySearch((mid + 1), high);
            else
             
                // f(mid) > 0
                return binarySearch(low, (mid -1));
        }
 
        /* Return -1 if there is no positive
        value in given range */
        return -1;
    }
     
    // Driver code
    public static void Main()
    {
       Console.Write ("The value n where f() " +
                      "becomes positive first is " +
                       findFirstPositive());
    }
}
 
// This code is contributed by nitin mittal


PHP
 0)
        return 0;
 
    // Find 'high' for binary
    // search by repeated doubling
    $i = 1;
    while (f($i) <= 0)
        $i = $i * 2;
 
    // Call binary search
    return binarySearch(intval($i / 2), $i);
}
 
// Searches first positive value
// of f(i) where low <= i <= high
function binarySearch($low, $high)
{
    if ($high >= $low)
    {
        /* mid = (low + high)/2 */
        $mid = $low + intval(($high -
                              $low) / 2);
 
        // If f(mid) is greater than 0
        // and one of the following two
        // conditions is true:
        // a) mid is equal to low
        // b) f(mid-1) is negative
        if (f($mid) > 0 && ($mid == $low ||
                          f($mid - 1) <= 0))
            return $mid;
 
        // If f(mid) is smaller
        // than or equal to 0
        if (f($mid) <= 0)
            return binarySearch(($mid + 1), $high);
        else // f(mid) > 0
            return binarySearch($low, ($mid - 1));
    }
 
    /* Return -1 if there is no
    positive value in given range */
    return -1;
}
 
// Driver Code
echo "The value n where f() becomes ".
                 "positive first is ".
                 findFirstPositive() ;
 
// This code is contributed by Sam007
?>


Javascript


输出 :

The value n where f() becomes positive first is 12

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程