📌  相关文章
📜  右侧最小的较大元素

📅  最后修改于: 2021-05-24 22:41:53             🧑  作者: Mango

给定一系列不同的元素,请为每个元素打印最接近的更大元素。元素x的最接近的较大元素是数组x中右侧大于x的最小元素。对于不存在更大元素的元素,请将下一个更大元素视为-1。

例子:

Input: arr[] = {4, 5, 2, 25}
Output: 
Element       NGE
   4      -->   5
   5      -->   25
   2      -->   25
   25     -->   -1

Input: arr[] = {4, 10, 7}
Output: 
Element       NGE
   4       -->  7
   10      -->   -1
   7       -->   -1

方法:在本文中,我们将讨论如何使用C++ STL(set)查找Next Greater Element。
在右侧找到最小的较大元素就像在已排序列表中找到当前元素的第一个较大元素一样。
考虑示例1,排序后的列表看起来像2、4、5、25。
在这里,对于元素4,较大的元素就是它旁边的5,因此我们打印5并删除4,因为它不再对其他元素更大,因为它不再在任何人的右边。
同样,对于5,它是25,我们从列表中删除了5,因为5不在2或25的右侧,因此可以将其删除。

下面给出查找每个索引元素的下一个更大元素的步骤。

  • 将所有元素插入Set中,它将按升序存储所有元素。
  • 循环访问元素数组,并为每个索引找到当前索引元素的upper_bound。 upper_bound()返回一个迭代器,该迭代器可以指向以下位置。
    1. 如果迭代器指向最后一个元素之后的位置,则当前索引元素不存在NGE。
    2. 如果迭代器指向引用某个元素的位置,则该元素是当前索引元素的NGE。
  • 找到每个遍历的当前索引元素的位置,并使用set的> lower_bound()和delete()函数将其从集合中删除。

下面是上述方法的实现。

C/C++
// C++ program to print the
// NGE's of array elements using
// C++ STL
#include 
using namespace std;
  
// Function to print the NGE
void printNGE(int a[], int n)
{
  
    set ms;
  
    // insert in the multiset container
    for (int i = 0; i < n; i++)
        ms.insert(a[i]);
  
    cout << "Element   "
         << "NGE";
  
    // traverse for all array elements
    for (int i = 0; i < n; i++) {
  
        // find the upper_bound in set
        auto it = ms.upper_bound(a[i]);
  
        // if points to the end, then
        // no NGE of that element
        if (it == ms.end()) {
            cout << "\n   " << a[i]
                 << " ----> " << -1;
        }
  
        // print the element at that position
        else {
            cout << "\n   " << a[i]
                 << " ----> " << *it;
        }
  
        // find the first occurrence of
        // the index element and delete it
        it = ms.lower_bound(a[i]);
  
        // delete one occurrence
        // from the container
        ms.erase(it);
    }
}
  
// Driver Code
int main()
{
    int a[] = { 4, 5, 2, 25 };
    int n = sizeof(a) / sizeof(a[0]);
  
    // Function call to print the NGE
    printNGE(a, n);
    return 0;
}


Java
// C++ program to print the
// NGE's of array elements using
import java.util.TreeSet;
  
class Geeks {
  
    // Function to print the NGE
    static void printNGE(int[] a, int n)
    {
  
        // Tree Set is an ordered set used to
        // store elements in a sorted manner
        TreeSet t = new TreeSet<>();
  
        // Adding elements into the set
        for (int i = 0; i < n; i++)
            t.add(a[i]);
  
        System.out.println("ELEMENT     NGE");
  
        for (int i = 0; i < n; i++) {
  
            // If the elements does not have an upper bound
            // or an element greater than it,
            // higher method of TreeSet class will return NULL
            if (t.higher(a[i]) == null)
                System.out.println(a[i] + " ----> "
                                   + "-1");
  
            // Otherwise print the upper bound of that element
            else
                System.out.println(a[i] + " ----> " + t.higher(a[i]));
  
            // Remove the current element from the set
            t.remove(a[i]);
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        int a[] = { 4, 5, 2, 25 };
        int n = a.length;
  
        printNGE(a, n);
    }
}


Python3
# Python3 program to print the
# NGE's of array elements
from bisect import bisect_right as upper_bound, \
                   bisect_left as lower_bound
  
# Function to print the NGE
def printNGE(a: list, n):
    ms = set()
  
    # insert in the multiset container
    for i in range(n):
        ms.add(a[i])
  
    print("Element NGE", end = "")
  
    # Required because Python sets
    # are not sorted
    new_arr = list(ms)
    new_arr.sort()
  
    # traverse for all array elements
    for i in range(n):
  
        # find the upper_bound in set
        it = upper_bound(new_arr, a[i])
  
        # if points to the end, then
        # no NGE of that element
        if (it == len(new_arr)):
            print("\n %d ----> -1" % a[i], end = "")
  
        # print the element at that position
        else:
            print("\n %d ----> %d" % (a[i], 
                    new_arr[it]), end = "")
  
        # find the first occurrence of
        # the index element and delete it
        it = lower_bound(new_arr, a[i])
  
        # delete one occurrence
        # from the container
        new_arr.remove(new_arr[it])
  
# Driver Code
if __name__ == "__main__":
    a = [4, 5, 2, 25]
    n = len(a)
  
    # Function call to print the NGE
    printNGE(a, n)
  
# This code is contributed by
# sanjeev2552


输出:
Element   NGE
   4 ----> 5
   5 ----> 25
   2 ----> 25
   25 ----> -1

时间复杂度: O(N log N)