📜  下一个更大的元素 |第 2 组(使用上限)

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

下一个更大的元素 |第 2 组(使用上限)

给定一个包含n 个整数的数组arr[ ] 。任务是使用 upper_bound()函数为数组中的每个数组元素找到第一个更大的元素。如果任何数组元素都没有更大的元素,则返回-1
例子 :

朴素方法:本文的第 1 组讨论了朴素方法和堆栈方法。在这里,我们讨论了使用 upper_bound() 解决它的方法。

方法:由于不能在未排序的数组中应用upper_bound()。这个想法是尝试修改数组以使其排序。因此,创建一个数组,让我们将其命名为copy[] ,它将以排序方式包含其元素。首先用0初始化copy[ ]并将 copy [ ]的每个元素更新为: copy[i] = max(copy[i-1], arr[i]) 。现在,upper_bound( ) 可以应用于副本 [ ]并为每个arr[i]找到第一个更大的元素。请按照以下步骤解决问题:

  • 使用值0初始化数组copy[n]
  • 使用变量i迭代范围[1, n)并执行以下步骤:
    • copy[i]的值设置为copy[i-1]arr[i] 的最大值。
  • 使用变量i遍历范围[0, n)并执行以下步骤:
    • 将变量high初始化为copy[]数组中arr[i]的上限。
    • 如果high等于n则打印-1否则打印arr[high]。

下面是上述方法的实现:

C++
// c++ implementation of  the above approach
#include 
using namespace std;
 
// Function to find first greater
// element for every element of array
void FirstGreater(int arr[], int n)
{
 
    // Creating copy array
    int copy[n];
 
    // Initializing all element of it with zero
    memset(copy, 0, sizeof(copy));
 
    copy[0] = arr[0];
 
    for (int i = 1; i < n; i++) {
 
        // Updating element of copy[]
        copy[i] = max(copy[i - 1], arr[i]);
    }
 
    for (int i = 0; i < n; i++) {
 
        // High stores the index of first greater
        // for every element of arr[]
        int high
            = upper_bound(copy,
                          copy + n, arr[i])
              - copy;
      
 
        // If there no element
        // is greater than arr[i]
        // print -1
        if (high == n) {
            cout << "-1"
                 << " ";
        }
 
        // Otherwisw print the first element
        // which is greater than arr[i]
        else {
            cout << arr[high] << " ";
        }
    }
}
 
// Driver Code
int main()
{
 
    int arr[] = { 4, 7, 3, 1, 3, 2, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    FirstGreater(arr, n);
    return 0;
}


Java
// Java code for the above approach
import java.io.*;
class GFG {
    static int upper_bound(int arr[], int N, int X)
    {
        int mid;
 
        // Initialise starting index and
        // ending index
        int low = 0;
        int high = N;
 
        // Till low is less than high
        while (low < high)
        {
           
            // Find the middle index
            mid = low + (high - low) / 2;
 
            // If X is greater than or equal
            // to arr[mid] then find
            // in right subarray
            if (X >= arr[mid]) {
                low = mid + 1;
            }
 
            // If X is less than arr[mid]
            // then find in left subarray
            else {
                high = mid;
            }
        }
 
        // if X is greater than arr[n-1]
        if (low < N && arr[low] <= X) {
            low++;
        }
 
        // Return the upper_bound index
        return low;
    }
   
    // Function to find first greater
    // element for every element of array
    static void FirstGreater(int arr[], int n)
    {
       
        // Creating copy array
        int copy[] = new int[n];
 
        copy[0] = arr[0];
        for (int i = 1; i < n; i++)
        {
           
            // Updating element of copy[]
            copy[i] = Math.max(copy[i - 1], arr[i]);
        }
        for (int i = 0; i < n; i++)
        {
           
            // High stores the index of first greater
            // for every element of arr[]
            int high
                = upper_bound(copy, copy.length, arr[i]);
 
            // If there no element
            // is greater than arr[i]
            // print -1
            if (high == n) {
                System.out.print("-1"
                                 + " ");
            }
           
            // Otherwisw print the first element
            // which is greater than arr[i]
            else {
                System.out.print(arr[high] + " ");
            }
        }
    }
   
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 4, 7, 3, 1, 3, 2, 5 };
        int n = arr.length;
        FirstGreater(arr, n);
    }
}
 
// This code is contributed by Potta Lokesh


Python3
# Python 3 implementation of  the above approach
import bisect
 
# Function to find first greater
# element for every element of array
def FirstGreater(arr, n):
 
    # Creating copy array
    copy = [0]*n
 
    copy[0] = arr[0]
 
    for i in range(1, n):
 
        # Updating element of copy[]
        copy[i] = max(copy[i - 1], arr[i])
 
    for i in range(n):
 
        # High stores the index of first greater
        # for every element of arr[]
        high = bisect.bisect_right(copy, arr[i], 0, n)
 
        # If there no element
        # is greater than arr[i]
        # print -1
        if (high == n):
            print("-1", end=" ")
 
        # Otherwisw print the first element
        # which is greater than arr[i]
        else:
            print(arr[high], end=" ")
 
# Driver Code
if __name__ == "__main__":
 
    arr = [4, 7, 3, 1, 3, 2, 5]
    n = len(arr)
    FirstGreater(arr, n)
 
    # This code is contributed by ukasp.


C#
// C# code for the above approach
using System;
 
public class GFG
{
    static int upper_bound(int []arr, int N, int X)
    {
        int mid;
 
        // Initialise starting index and
        // ending index
        int low = 0;
        int high = N;
 
        // Till low is less than high
        while (low < high)
        {
           
            // Find the middle index
            mid = low + (high - low) / 2;
 
            // If X is greater than or equal
            // to arr[mid] then find
            // in right subarray
            if (X >= arr[mid]) {
                low = mid + 1;
            }
 
            // If X is less than arr[mid]
            // then find in left subarray
            else {
                high = mid;
            }
        }
 
        // if X is greater than arr[n-1]
        if (low < N && arr[low] <= X) {
            low++;
        }
 
        // Return the upper_bound index
        return low;
    }
   
    // Function to find first greater
    // element for every element of array
    static void FirstGreater(int []arr, int n)
    {
       
        // Creating copy array
        int []copy = new int[n];
 
        copy[0] = arr[0];
        for (int i = 1; i < n; i++)
        {
           
            // Updating element of copy[]
            copy[i] = Math.Max(copy[i - 1], arr[i]);
        }
        for (int i = 0; i < n; i++)
        {
           
            // High stores the index of first greater
            // for every element of []arr
            int high
                = upper_bound(copy, copy.Length, arr[i]);
 
            // If there no element
            // is greater than arr[i]
            // print -1
            if (high == n) {
                Console.Write("-1"
                                 + " ");
            }
           
            // Otherwisw print the first element
            // which is greater than arr[i]
            else {
                Console.Write(arr[high] + " ");
            }
        }
    }
   
    // Driver Code
    public static void Main(String[] args)
    {
        int []arr = { 4, 7, 3, 1, 3, 2, 5 };
        int n = arr.Length;
        FirstGreater(arr, n);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出
7 -1 4 4 4 4 7 

时间复杂度: O(n*log(n))
辅助空间: O(n)