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

📅  最后修改于: 2021-05-19 19:13:00             🧑  作者: Mango

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

例子 :

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

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

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

  1. 创建一个空的Set 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 prthe 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


输出:
0 1 1 1 4 1 2












时间复杂度: O(N 2 ),因为距离函数取O(N),但上述实现非常简单,并且比一般情况下的朴素算法好。
辅助空间: O(N)

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