📌  相关文章
📜  在每个数组元素的左侧计算更大的元素

📅  最后修改于: 2021-10-28 01:45:33             🧑  作者: Mango

给定大小为N的不同整数的数组arr[] ,任务是在每个数组元素的左侧打印更大元素的计数。

例子 :

朴素的方法:解决问题的最简单方法是遍历数组,对于每个数组元素,向左遍历并将每个元素与当前元素进行比较。最后,为每个数组元素在其左侧打印更大元素的计数。

时间复杂度: O(N 2 )
辅助空间: O(1)

有效的方法:可以使用由自平衡二叉搜索树实现的 Set 容器来解决该问题。请按照以下步骤解决问题。

  1. 创建一个空集St
  2. 遍历数组,将St 中的每个元素一一插入。
  3. 使用 upper_bound函数查找arr[i]的前一个较大元素。
  4. 使用距离函数查找集合中前一个较大元素和最后一个元素之间的距离。
  5. 将距离存储在数组countLeftGreater[] 中
  6. 打印数组。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to print the count of greater
// elements on left of each array element
void display(int countLeftGreater[], int N)
{
    for (int i = 0; i < N; i++) {
        cout << countLeftGreater[i]
             << " ";
    }
}
 
// Function to get the count of greater
// elements on left of each array element
void countGreater(int arr[], int N)
{
    // Store distinct array
    // elements in sorted order
    set St;
 
    // Stores the count of greater
    // elements on the left side
    int countLeftGreater[N];
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Insert array elements
        // into the set
        St.insert(arr[i]);
 
        // Find previous greater element
        auto it = St.upper_bound(arr[i]);
 
        // Find the distance between the
        // previous greater element of arr[i]
        // and last element of the set
        countLeftGreater[i]
            = distance(it, St.end());
    }
    display(countLeftGreater, N);
}
 
// Driver Code
int main()
{
    int arr[] = { 12, 1, 2, 3, 0, 11, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
    countGreater(arr, N);
}


Java
// Java program to implement
// the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
     
// Function to print the count of greater
// elements on left of each array element
static void display(int countLeftGreater[], int N)
{
    for(int i = 0; i < N; i++)
    {
       System.out.print(countLeftGreater[i] + " ");
    }
}
   
// Function to get the count of greater
// elements on left of each array element
static void countGreater(int arr[], int N)
{
     
    // Store distinct array
    // elements in sorted order
    Set St = new TreeSet<>();
   
    // Stores the count of greater
    // elements on the left side
    int[] countLeftGreater = new int[N];
   
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Insert array elements
        // into the set
        St.add(arr[i]);
   
        int it = 0;
         
        // Find previous greater element
        Iterator iterator = St.iterator();
        while (iterator.hasNext())
        {
           if (arr[i] < iterator.next())
           {
               break;
           }
           it++;
        }
   
        // Find the distance between the
        // previous greater element of arr[i]
        // and last element of the set
        countLeftGreater[i] = Math.abs(it - St.size());
    }
    display(countLeftGreater, N); 
}
 
// Driver code
public static void main (String[] args)
{
    int arr[] = { 12, 1, 2, 3, 0, 11, 4 };
    int N = arr.length;
     
    countGreater(arr, N);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program to implement
# the above approach
 
# Function to print the count of greater
# elements on left of each array element
def display(countLeftGreater, N):
     
    for i in range(N):
        print(countLeftGreater[i], end = " ")
 
# Function to get the count of greater
# elements on left of each array element
def countGreater(arr, N):
     
    # Store distinct array
    # elements in sorted order
    St = set()
 
    # Stores the count of greater
    # elements on the left side
    countLeftGreater = [0] * (N)
     
    # Traverse the array
    for i in range(N):
         
        # Insert array elements
        # into the set
        St.add(arr[i])
 
        it = 0
 
        # Find previous greater element
        for st in St:
            if (arr[i] < st):
                break
 
            it += 1
        # Find the distance between the
        # previous greater element of arr[i]
        # and last element of the set
        countLeftGreater[i] = abs(it - len(St))
 
    display(countLeftGreater, N)
 
# Driver code
if __name__ == '__main__':
     
    arr = [ 12, 1, 2, 3, 0, 11, 4 ]
    N = len(arr)
 
    countGreater(arr, N)
 
# This code is contributed by Rajput-Ji


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to print the count of greater
// elements on left of each array element
static void display(int []countLeftGreater, int N)
{
    for(int i = 0; i < N; i++)
    {
        Console.Write(countLeftGreater[i] + " ");
    }
}
   
// Function to get the count of greater
// elements on left of each array element
static void countGreater(int []arr, int N)
{
     
    // Store distinct array
    // elements in sorted order
    List St = new List();
   
    // Stores the count of greater
    // elements on the left side
    int[] countLeftGreater = new int[N];
   
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Insert array elements
        // into the set
        St.Add(arr[i]);
   
        int it = 0;
        St.Sort();
         
        // Find previous greater element
        foreach(int itr in St)
        {
            if (arr[i] < itr)
            {
                break;
            }
            it++;
        }
         
        // Find the distance between the
        // previous greater element of arr[i]
        // and last element of the set
        countLeftGreater[i] = Math.Abs(it - St.Count);
    }
    display(countLeftGreater, N); 
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 12, 1, 2, 3, 0, 11, 4 };
    int N = arr.Length;
     
    countGreater(arr, N);
}
}
 
// This code is contributed by gauravrajput1


Javascript


输出:
0 1 1 1 4 1 2

时间复杂度: O(N 2 ) 因为距离函数需要O(N)但是上面的实现非常简单并且在一般情况下比朴素算法效果更好。
辅助空间: O(N)

注意:上述方法适用于唯一元素,但对于重复元素,只需将 Set 替换为 Multiset。

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