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

📅  最后修改于: 2021-10-27 07:03:10             🧑  作者: Mango

给定一个由N 个不同整数组成的数组arr[] ,任务是为每个数组元素打印其左侧存在的所有较大元素

例子:

朴素的方法:解决问题的最简单方法是遍历数组,对于每个数组元素,遍历其前面的所有元素并打印大于当前元素的元素。

C++
// C++ program for Naive approach
#include 
using namespace std;
 
// Function to print all greater elements on the left of each array element
void printGreater(vector& arr)
{
    // store the size of array in variable n
    int n = arr.size();
    for (int i = 0; i < n; i++)
    {
        // result is used to store elements which are greater than current element present left side of current element
        vector result;
 
        // traversing all the elements which are left of current element arr[i]
       
        for (int j = i - 1; j >= 0; j--)
        {
            //checking whether arr[j] (left element) is greater than current element or not
            // if yes then insert the element to the result vector
            if (arr[j] > arr[i])
            {
                result.push_back(arr[j]);
            }
        }
        cout << arr[i] << ": ";
       
        //printing all the elements present in result vector
        for (int k = 0; k < result.size(); k++)
        {
            cout << result[k] << " ";
        }
        cout << endl;
    }
}
 
//Driver Code
int main()
{
    vector arr{5, 3, 9, 0, 16, 12};
    printGreater(arr);
    return 0;
}


Java
// java program for Naive approach
import java.util.*;
 
class GFG{
 
  // Function to print all greater elements on the left of each array element
  static void printGreater(ArrayList arr)
  {
    // store the size of array in variable n
    int n = arr.size();
    for (int i = 0; i < n; i++)
    {
       
      // result is used to store elements which
      // are greater than current element present
      // left side of current element
      ArrayList result
        = new ArrayList();
 
      // traversing all the elements which
      // are left of current element arr[i]
 
      for (int j = i - 1; j >= 0; j--)
      {
        // checking whether arr[j] (left element) is
        // greater than current element or not
        // if yes then insert the element to the result vector
        if (arr.get(j) > arr.get(i))
        {
          result.add(arr.get(j));
        }
      }
      System.out.print(arr.get(i) + ": ");
 
      // printing all the elements present in result vector
      for (int k = 0; k < result.size(); k++)
      {
        System.out.print(result.get(k) +" ");
      }
      System.out.println();
    }
  }
 
  // Driver Code
  public static void main(String args[])
  {
    ArrayList arr = new ArrayList(Arrays.asList(5, 3, 9, 0, 16, 12));
    printGreater(arr);
  }
}
 
// This code is contributed by bgangwar59.


Python3
# Python3 program for Naive approach
 
# Function to print all greater
# elements on the left of each
# array element
def printGreater(arr):
     
    # Store the size of array
    # in variable n
    n = len(arr)
     
    for i in range(n):
         
        # Result is used to store elements
        # which are greater than current
        # element present left side of
        # current element
        result = []
 
        # Traversing all the elements
        # which are left of current
        # element arr[i]
        j = i - 1
         
        while(j >= 0):
             
            # Checking whether arr[j] (left element)
            # is greater than current element or not
            # if yes then insert the element to the
            # result vector
            if (arr[j] > arr[i]):
                result.append(arr[j])
                 
            j -= 1
             
        print(arr[i], end = ": ")
       
        # Printing all the elements present
        # in result vector
        for k in range(len(result)):
            print(result[k], end = " ")
             
        print("\n", end = "")
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 5, 3, 9, 0, 16, 12 ]
     
    printGreater(arr)
 
# This code is contributed by ipg2016107


C#
// C# program for Naive approach
using System;
using System.Collections.Generic;
class GFG
{
   
    // Function to print all greater elements on the left of
    // each array element
    static void printGreater(int[] arr)
    {
       
        // store the size of array in variable n
        int n = arr.Length;
        for (int i = 0; i < n; i++)
        {
           
            // result is used to store elements which are
            // greater than current element present left
            // side of current element
            List result = new List();
 
            // traversing all the elements which are left of
            // current element arr[i]
 
            for (int j = i - 1; j >= 0; j--)
            {
               
                // checking whether arr[j] (left element) is
                // greater than current element or not
                // if yes then insert the element to the
                // result vector
                if (arr[j] > arr[i]) {
                    result.Add(arr[j]);
                }
            }
            Console.Write(arr[i] + ": ");
 
            // printing all the elements present in result
            // vector
            for (int k = 0; k < result.Count; k++) {
                Console.Write(result[k] + " ");
            }
            Console.WriteLine();
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 5, 3, 9, 0, 16, 12 };
        printGreater(arr);
    }
}
 
// This code is contributed by ukasp.


Javascript


C++
// C++ Program for the above approach
#include 
using namespace std;
 
// Function to print all greater elements
// on the left of each array element
void printGreater(vector& arr)
{
    int n = arr.size();
 
    // Set to implement
    // self-balancing BSTs
    set > s;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // Insert the current
        // element into the set
        auto p = s.insert(arr[i]);
        auto j = s.begin();
 
        cout << arr[i] << ": ";
 
        // Iterate through the set
        while (j != p.first) {
 
            // Print the element
            cout << *j << " ";
            j++;
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    vector arr{ 5, 3, 9, 0, 16, 12 };
    printGreater(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to print all greater elements
// on the left of each array element
static void printGreater(int arr[])
{
    int n = arr.length;
 
    // Set to implement
    // self-balancing BSTs
    TreeSet s = new TreeSet<>(
        Collections.reverseOrder());
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
         
        // Insert the current
        // element into the set
        s.add(arr[i]);
 
        System.out.print(arr[i] + ": ");
 
        // Iterate through the set
        for(int v : s)
        {
            if (v == arr[i])
                break;
 
            // Print the element
            System.out.print(v + " ");
        }
        System.out.println();
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 5, 3, 9, 0, 16, 12 };
    printGreater(arr);
}
}
 
// This code is contributed by Kingash


Javascript


输出
5: 
3: 5 
9: 
0: 9 3 5 
16: 
12: 16 

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

高效方法:为了优化上述方法,其想法是利用自平衡二叉搜索树。 C++中的Set是使用自平衡BSTs实现的,可以用来解决这个问题。请按照以下步骤解决问题:

  • 初始化一个 Set s ,以非递减顺序存储元素。
  • 在索引0N – 1 上遍历数组并执行以下操作:
    • arr[i]插入到集合s 中
    • 从 Set 的开头迭代到p并打印 Set 中的元素。

下面是上述方法的实现:

C++

// C++ Program for the above approach
#include 
using namespace std;
 
// Function to print all greater elements
// on the left of each array element
void printGreater(vector& arr)
{
    int n = arr.size();
 
    // Set to implement
    // self-balancing BSTs
    set > s;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // Insert the current
        // element into the set
        auto p = s.insert(arr[i]);
        auto j = s.begin();
 
        cout << arr[i] << ": ";
 
        // Iterate through the set
        while (j != p.first) {
 
            // Print the element
            cout << *j << " ";
            j++;
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    vector arr{ 5, 3, 9, 0, 16, 12 };
    printGreater(arr);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to print all greater elements
// on the left of each array element
static void printGreater(int arr[])
{
    int n = arr.length;
 
    // Set to implement
    // self-balancing BSTs
    TreeSet s = new TreeSet<>(
        Collections.reverseOrder());
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
         
        // Insert the current
        // element into the set
        s.add(arr[i]);
 
        System.out.print(arr[i] + ": ");
 
        // Iterate through the set
        for(int v : s)
        {
            if (v == arr[i])
                break;
 
            // Print the element
            System.out.print(v + " ");
        }
        System.out.println();
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 5, 3, 9, 0, 16, 12 };
    printGreater(arr);
}
}
 
// This code is contributed by Kingash

Javascript


输出
5: 
3: 5 
9: 
0: 9 5 3 
16: 
12: 16 

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