📌  相关文章
📜  C++ 的lower_bound() 方法的Java等效项

📅  最后修改于: 2022-05-13 01:54:32.584000             🧑  作者: Mango

C++ 的lower_bound() 方法的Java等效项

C++ 的lower_bound() 方法返回数组中第一个值不小于key 的元素的索引。这意味着该函数返回刚好大于或等于该数字的下一个最小数字的索引。如果有多个值等于该数字,lower_bound() 将返回第一个此类值的索引。

例子:

Input  : 4 6 10 12 18 18 20 20 30 45
Output : lower_bound for element 18 at index 4
Input  : 4 6 10 12 16 20 28
Output : lower_bound for element 18 at index 5
Input  : 24 26 40 56
Output : lower_bound for element 18 at index 0
Input  : 4 6 10 12 16 17
Output : lower_bound for element 18 at index 6

现在让我们讨论一下方法,以便使用下界()方法来获得下一个刚好大于或等于该数字的最小数字的索引。

方法:

  1. 天真的方法
  2. 迭代使用二分查找
  3. 递归使用二分查找
  4. 使用 Arrays 实用程序类的 binarySearch() 方法

方法一:使用线性搜索



方法:

我们可以使用线性搜索来找到下界。我们将从第 0 个索引开始迭代数组,直到找到等于或大于键的值。

例子

Java
// Java program for finding lower bound
// using linear search
  
// Importing Arrays utility class
import java.util.Arrays;
  
// Main class
class GFG {
  
    // Method 1
    // To find lower bound of given key
    static int lower(int array[], int key)
    {
        int lowerBound = 0;
  
        // Traversing the array using length function
        while (lowerBound < array.length) {
  
            // If key is lesser than currnet value
            if (key > array[lowerBound])
                lowerBound++;
  
            // This is either the first occurrence of key
            // or value just greater than key
            else
                return lowerBound;
        }
  
        return lowerBound;
    }
  
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom array input over which lower bound is to
        // be operated by passing a key
        int array[]
            = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 };
        int key = 18;
  
        // Sort the array using Arrays.sort() method
        Arrays.sort(array);
  
        // Printing the lower bound
        System.out.println(lower(array, key));
    }
}


Java
// Java program to Find lower bound
// Using Binary Search Iteratively
  
// Importing Arrays utility class
import java.util.Arrays;
  
// Main class
public class GFG {
  
    // Method 1
    // Iterative approach to find lower bound
    // using binary search technique
    static int lower_bound(int array[], int key)
    {
        // Initialize starting index and
        // ending index
        int low = 0, high = array.length;
        int mid;
  
        // Till high does not crosses low
        while (low < high) {
  
            // Find the index of the middle element
            mid = low + (high - low) / 2;
  
            // If key is less than or equal
            // to array[mid], then find in
            // left subarray
            if (key <= array[mid]) {
                high = mid;
            }
  
            // If key is greater than array[mid],
            // then find in right subarray
            else {
  
                low = mid + 1;
            }
        }
  
        // If key is greater than last element which is
        // array[n-1] then lower bound
        // does not exists in the array
        if (low < array.length && array[low] < key) {
            low++;
        }
  
        // Returning the lower_bound index
        return low;
    }
  
    // Method 2
    // Driver main method
    public static void main(String[] args)
    {
  
        // Custom array and key input over which lower bound
        // is computed
        int array[]
            = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 };
        int key = 18;
  
        // Sort the array  using Arrays.sort() method
        Arrays.sort(array);
  
        // Printing the lower bound
        System.out.println(lower_bound(array, key));
    }
}


Java
// Java program to Find Lower Bound
// Using Binary Search Recursively
  
// Importing Arrays utility class
import java.util.Arrays;
  
// Main class
public class GFG {
  
    // Method 1
    // To find lower bound using binary search technique
    static int recursive_lower_bound(int array[], int low,
                                     int high, int key)
    {
        // Base Case
        if (low > high) {
            return low;
        }
  
        // Find the middle index
        int mid = low + (high - low) / 2;
  
        // If key is lesser than or equal to
        // array[mid] , then search
        // in left subarray
        if (key <= array[mid]) {
  
            return recursive_lower_bound(array, low,
                                         mid - 1, key);
        }
  
        // If key is greater than array[mid],
        // then find in right subarray
        return recursive_lower_bound(array, mid + 1, high,
                                     key);
    }
  
    // Method 2
    // To compute the lower bound
    static int lower_bound(int array[], int key)
    {
        // Initialize starting index and
        // ending index
        int low = 0, high = array.length;
  
        // Call recursive lower bound method
        return recursive_lower_bound(array, low, high, key);
    }
  
    // Method 3
    // Main driver method
    public static void main(String[] args)
    {
        // Custom array and key over which lower bound is to
        // be computed
        int array[]
            = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 };
        int key = 18;
  
        // Sorting the array using Arrays.sort() method
        Arrays.sort(array);
  
        // Printing the lower bound
        System.out.println(lower_bound(array, key));
    }
}


Java
// Java program to find lower bound
// using binarySearch() method of Arrays class
  
// Importing Arrays utility class
import java.util.Arrays;
  
// Main class
public class GFG {
  
    // Method 1
    // To find lower bound using binary search
    // implementation of Arrays utility class
    static int lower_bound(int array[], int key)
    {
  
        int index = Arrays.binarySearch(array, key);
  
        // If key is not present in the array
        if (index < 0) {
  
            // Index specify the position of the key
            // when inserted in the sorted array
            // so the element currently present at
            // this position will be the lower bound
            return Math.abs(index) - 1;
        }
  
        // If key is present in the array
        // we move leftwards to find its first occurrence
        else {
  
            // Decrement the index to find the first
            // occurrence of the key
  
            while (index > 0) {
  
                // If previous value is same
                if (array[index - 1] == key)
                    index--;
  
                // Previous value is different which means
                // current index is the first occurrence of
                // the key
                else
                    return index;
            }
  
            return index;
        }
    }
  
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        //
        int array[]
            = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 };
        int key = 18;
  
        // Sort the array before applying binary search
        Arrays.sort(array);
        
        // Printing the lower bound 
        System.out.println(lower_bound(array, key));
    }
}


输出
4

我们可以使用一种有效的二分搜索方法在O(log 2 n) 中搜索排序数组中的键,如下例所示

方法二:迭代使用二分查找



程序:

  1. 将低初始化为 0,将高初始化为 N。
  2. 比较key和中间元素(arr[mid])
  3. 如果中间元素大于或等于键,则将高更新为中间索引(mid)。
  4. 否则将低更新为中 + 1。
  5. 重复步骤 2 到步骤 4,直到低小于高。
  6. 在所有上述步骤之后,low 是给定数组中某个键的下界。

例子

Java

// Java program to Find lower bound
// Using Binary Search Iteratively
  
// Importing Arrays utility class
import java.util.Arrays;
  
// Main class
public class GFG {
  
    // Method 1
    // Iterative approach to find lower bound
    // using binary search technique
    static int lower_bound(int array[], int key)
    {
        // Initialize starting index and
        // ending index
        int low = 0, high = array.length;
        int mid;
  
        // Till high does not crosses low
        while (low < high) {
  
            // Find the index of the middle element
            mid = low + (high - low) / 2;
  
            // If key is less than or equal
            // to array[mid], then find in
            // left subarray
            if (key <= array[mid]) {
                high = mid;
            }
  
            // If key is greater than array[mid],
            // then find in right subarray
            else {
  
                low = mid + 1;
            }
        }
  
        // If key is greater than last element which is
        // array[n-1] then lower bound
        // does not exists in the array
        if (low < array.length && array[low] < key) {
            low++;
        }
  
        // Returning the lower_bound index
        return low;
    }
  
    // Method 2
    // Driver main method
    public static void main(String[] args)
    {
  
        // Custom array and key input over which lower bound
        // is computed
        int array[]
            = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 };
        int key = 18;
  
        // Sort the array  using Arrays.sort() method
        Arrays.sort(array);
  
        // Printing the lower bound
        System.out.println(lower_bound(array, key));
    }
}
输出
4

现在像往常一样,通过遵循与上述相同的过程提供递归方法来进一步优化。

方法三:递归使用二分查找

Java

// Java program to Find Lower Bound
// Using Binary Search Recursively
  
// Importing Arrays utility class
import java.util.Arrays;
  
// Main class
public class GFG {
  
    // Method 1
    // To find lower bound using binary search technique
    static int recursive_lower_bound(int array[], int low,
                                     int high, int key)
    {
        // Base Case
        if (low > high) {
            return low;
        }
  
        // Find the middle index
        int mid = low + (high - low) / 2;
  
        // If key is lesser than or equal to
        // array[mid] , then search
        // in left subarray
        if (key <= array[mid]) {
  
            return recursive_lower_bound(array, low,
                                         mid - 1, key);
        }
  
        // If key is greater than array[mid],
        // then find in right subarray
        return recursive_lower_bound(array, mid + 1, high,
                                     key);
    }
  
    // Method 2
    // To compute the lower bound
    static int lower_bound(int array[], int key)
    {
        // Initialize starting index and
        // ending index
        int low = 0, high = array.length;
  
        // Call recursive lower bound method
        return recursive_lower_bound(array, low, high, key);
    }
  
    // Method 3
    // Main driver method
    public static void main(String[] args)
    {
        // Custom array and key over which lower bound is to
        // be computed
        int array[]
            = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 };
        int key = 18;
  
        // Sorting the array using Arrays.sort() method
        Arrays.sort(array);
  
        // Printing the lower bound
        System.out.println(lower_bound(array, key));
    }
}
输出
4

方法 4:使用 Arrays 实用程序类的 binarySearch() 方法

我们还可以使用 Arrays 实用程序类(或 Collections 实用程序类)的内置二进制搜索实现。该函数返回搜索键的索引(如果它包含在数组中);否则,(-(插入点) – 1)。插入点定义为将键插入数组的点。

方法:

  1. 在已排序的数组中搜索键的索引,返回该键的索引,因为它存在于数组中的正值,否则返回指定的负值。
  2. 应在排序数组中添加键的位置。
  3. 现在,如果键存在于数组中,我们向左移动以找到它的第一次出现,否则减少索引以找到键的第一次出现。
  4. 在应用二分搜索之前对数组进行排序
  5. 打印出来

例子

Java

// Java program to find lower bound
// using binarySearch() method of Arrays class
  
// Importing Arrays utility class
import java.util.Arrays;
  
// Main class
public class GFG {
  
    // Method 1
    // To find lower bound using binary search
    // implementation of Arrays utility class
    static int lower_bound(int array[], int key)
    {
  
        int index = Arrays.binarySearch(array, key);
  
        // If key is not present in the array
        if (index < 0) {
  
            // Index specify the position of the key
            // when inserted in the sorted array
            // so the element currently present at
            // this position will be the lower bound
            return Math.abs(index) - 1;
        }
  
        // If key is present in the array
        // we move leftwards to find its first occurrence
        else {
  
            // Decrement the index to find the first
            // occurrence of the key
  
            while (index > 0) {
  
                // If previous value is same
                if (array[index - 1] == key)
                    index--;
  
                // Previous value is different which means
                // current index is the first occurrence of
                // the key
                else
                    return index;
            }
  
            return index;
        }
    }
  
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        //
        int array[]
            = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 };
        int key = 18;
  
        // Sort the array before applying binary search
        Arrays.sort(array);
        
        // Printing the lower bound 
        System.out.println(lower_bound(array, key));
    }
}
输出
4
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程