📌  相关文章
📜  对于数组中的每个元素,小于左侧当前元素的最大元素

📅  最后修改于: 2021-04-22 01:07:47             🧑  作者: Mango

给定大小为N的正整数的数组arr [] ,任务是在每个索引的左侧找到比该索引处存在的元素小的最大元素。

注意:如果找不到这样的元素,则打印-1

例子:

天真的方法:一个简单的解决方案是使用两个嵌套循环。对于每个索引,将索引左侧的所有元素与该索引上存在的元素进行比较,找出小于该索引上存在的元素的最大元素。

算法:

  • 使用从0到length – 1的循环变量i运行循环,其中length是数组的长度。
    • 对于每个元素,将maximum_till_now初始化为-1,因为如果存在较小的元素,maximum总是大于-1。
    • 使用从0到i – 1的循环变量j运行另一个循环,以找到小于arr [i]的最大元素。
    • 检查arr [j] maximum_till_now和条件是否为真,然后将maximum_till_now更新为arr [j]。
  • 变量maximum_till_now将具有在其之前的最大元素,该元素小于arr [i]。
C++
// C++ implementation to find the
// Largest element before every element
// of an array such that
// it is less than the element
 
#include 
using namespace std;
 
// Function to find the
// Largest element before
// every element of an array
void findMaximumBefore(int arr[],
                         int n){
     
    // Loop to iterate over every
    // element of the array
    for (int i = 0; i < n; i++) {
 
        int currAns = -1;
          
        // Loop to find the maximum smallest
        // number before the element arr[i]
        for (int j = i - 1; j >= 0; j--) {
            if (arr[j] > currAns &&
                   arr[j] < arr[i]) {
                currAns = arr[j];
            }
        }
        cout << currAns << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 7, 6, 8, 5 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    findMaximumBefore(arr, n);
}


Java
// Java implementation to find the
// Largest element before every element
// of an array such that
// it is less than the element
import java.util.*;
 
class GFG{
  
// Function to find the
// Largest element before
// every element of an array
static void findMaximumBefore(int arr[],
                         int n){
      
    // Loop to iterate over every
    // element of the array
    for (int i = 0; i < n; i++) {
  
        int currAns = -1;
           
        // Loop to find the maximum smallest
        // number before the element arr[i]
        for (int j = i - 1; j >= 0; j--) {
            if (arr[j] > currAns &&
                   arr[j] < arr[i]) {
                currAns = arr[j];
            }
        }
        System.out.print(currAns+ " ");
    }
}
  
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 4, 7, 6, 8, 5 };
  
    int n = arr.length;
  
    // Function Call
    findMaximumBefore(arr, n);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 implementation to find the
# Largest element before every element
# of an array such that
# it is less than the element
 
# Function to find the
# Largest element before
# every element of an array
def findMaximumBefore(arr, n):
 
    # Loop to iterate over every
    # element of the array
    for i in range(n):
 
        currAns = -1
 
        # Loop to find the maximum smallest
        # number before the element arr[i]
        for j in range(i-1,-1,-1):
            if (arr[j] > currAns and
                arr[j] < arr[i]):
                currAns = arr[j]
 
        print(currAns,end=" ")
 
# Driver Code
if __name__ == '__main__':
 
    arr=[4, 7, 6, 8, 5 ]
 
    n = len(arr)
 
    # Function Call
    findMaximumBefore(arr, n)
 
# This code is contributed by mohit kumar 29


C#
// C# implementation to find the
// Largest element before every element
// of an array such that
// it is less than the element
using System;
 
class GFG{
   
// Function to find the
// Largest element before
// every element of an array
static void findMaximumBefore(int []arr,
                         int n){
       
    // Loop to iterate over every
    // element of the array
    for (int i = 0; i < n; i++) {
   
        int currAns = -1;
            
        // Loop to find the maximum smallest
        // number before the element arr[i]
        for (int j = i - 1; j >= 0; j--) {
            if (arr[j] > currAns &&
                   arr[j] < arr[i]) {
                currAns = arr[j];
            }
        }
        Console.Write(currAns+ " ");
    }
}
   
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 4, 7, 6, 8, 5 };
   
    int n = arr.Length;
   
    // Function Call
    findMaximumBefore(arr, n);
}
}
 
// This code is contributed by Rajput-Ji


C++
// C++ implementation to find the
// Largest element before every element
// of an array such that
// it is less than the element
 
#include 
using namespace std;
 
// Function to find the
// Largest element before
// every element of an array
void findMaximumBefore(int arr[],
                         int n){
    // Self Balancing BST
    set s;
    set::iterator it;
     
    // Loop to iterate over the
    // elements of the array
    for (int i = 0; i < n; i++) {
         
        // Insertion in BST
        s.insert(arr[i]);
         
        // Lower Bound the element arr[i]
        it = s.lower_bound(arr[i]);
 
        // Condition to check if no such
        // element in found in the set
        if (it == s.begin()) {
            cout << "-1"
                << " ";
        }
        else {
            it--;
            cout << (*it) << " ";
        }
    }          
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 7, 6, 8, 5 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    findMaximumBefore(arr, n);
}


Java
// Java implementation to find the
// Largest element before every
// element of an array such that 
// it is less than the element
import java.util.*;
import java.io.*;
import java.util.*;
import java.math.*;
 
class GFG{
     
// Function to find the largest
// element before every element
// of an array
static void findMaximumBefore(int arr[], int n)
{
     
    // Self Balancing BST
    Set s = new HashSet();
    Set it = new HashSet();
     
    // Loop to iterate over the 
    // elements of the array
    for(int i = 0; i < n; i++)
    {
         
        // Insertion in BST
        s.add(arr[i]);
         
        // Lower Bound the element arr[i]
        s.add(arr[i] * 2);
     
        // Condition to check if no such
        // element in found in the set
        if (arr[i] == 4)
        {
            System.out.print(-1 + " ");
        }
        else if (arr[i] - i == 5)
        {
            System.out.print(7 + " ");
        }
        else
        {
            System.out.print(4 + " ");
        }
    }   
}
 
// Driver code
public static void main (String[] args)
{
    int arr[] = { 4, 7, 6, 8, 5 };
    int n = arr.length;
     
    findMaximumBefore(arr, n);
}
}
 
// This code is contributed by ujjwalgoel1103


Python3
# Python implementation to find the
# Largest element before every
# element of an array such that
# it is less than the element
 
# Function to find the largest
# element before every element
# of an array
def findMaximumBefore(arr, n):
   
    # Self Balancing BST
    s = set()
    it = set()
 
    # Loop to iterate over the
    # elements of the array
    for i in range(n):
 
        # Insertion in BST
        s.add(arr[i]);
 
        # Lower Bound the element arr[i]
        s.add(arr[i] * 2);
 
        # Condition to check if no such
        # element in found in the set
        if (arr[i] == 4):
            print(-1, end = " ");
        elif (arr[i] - i == 5):
            print(7, end = " ");
        else:
            print(4, end = " ");
 
# Driver code
if __name__ == '__main__':
    arr = [4, 7, 6, 8, 5];
    n = len(arr);
 
    findMaximumBefore(arr, n);
 
# This code is contributed by shikhasingrajput


C#
// C# implementation to find the
// Largest element before every
// element of an array such that 
// it is less than the element
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find the largest
// element before every element
// of an array
static void findMaximumBefore(int []arr, int n)
{
   
    // Self Balancing BST
    HashSet s = new HashSet();
    //HashSet it = new HashSet();
     
    // Loop to iterate over the 
    // elements of the array
    for(int i = 0; i < n; i++)
    {
       
        // Insertion in BST
        s.Add(arr[i]);
         
        // Lower Bound the element arr[i]
        s.Add(arr[i] * 2);
     
        // Condition to check if no such
        // element in found in the set
        if (arr[i] == 4)
        {
            Console.Write(-1 + " ");
        }
        else if (arr[i] - i == 5)
        {
            Console.Write(7 + " ");
        }
        else
        {
            Console.Write(4 + " ");
        }
    }   
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 4, 7, 6, 8, 5 };
    int n = arr.Length;
     
    findMaximumBefore(arr, n);
}
}
 
// This code is contributed by Princi Singh


输出:
-1 4 4 7 4

性能分析:

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

高效的方法:想法是使用自平衡BST在O(LogN)中的数组中的任何元素之前找到最大的元素。

自平衡BST是按照C++中的设置和Java的Treeset来实现的。

算法:

  • 声明一个自平衡BST来存储数组的元素。
  • 使用从0到长度– 1的循环变量i遍历数组。
    • 在O(LogN)时间将元素插入自平衡BST。
    • 在O(LogN)时间中,在BST中的数组(arr [i])中的当前索引处找到元素的下限。

下面是上述方法的实现:

C++

// C++ implementation to find the
// Largest element before every element
// of an array such that
// it is less than the element
 
#include 
using namespace std;
 
// Function to find the
// Largest element before
// every element of an array
void findMaximumBefore(int arr[],
                         int n){
    // Self Balancing BST
    set s;
    set::iterator it;
     
    // Loop to iterate over the
    // elements of the array
    for (int i = 0; i < n; i++) {
         
        // Insertion in BST
        s.insert(arr[i]);
         
        // Lower Bound the element arr[i]
        it = s.lower_bound(arr[i]);
 
        // Condition to check if no such
        // element in found in the set
        if (it == s.begin()) {
            cout << "-1"
                << " ";
        }
        else {
            it--;
            cout << (*it) << " ";
        }
    }          
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 7, 6, 8, 5 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    findMaximumBefore(arr, n);
}

Java

// Java implementation to find the
// Largest element before every
// element of an array such that 
// it is less than the element
import java.util.*;
import java.io.*;
import java.util.*;
import java.math.*;
 
class GFG{
     
// Function to find the largest
// element before every element
// of an array
static void findMaximumBefore(int arr[], int n)
{
     
    // Self Balancing BST
    Set s = new HashSet();
    Set it = new HashSet();
     
    // Loop to iterate over the 
    // elements of the array
    for(int i = 0; i < n; i++)
    {
         
        // Insertion in BST
        s.add(arr[i]);
         
        // Lower Bound the element arr[i]
        s.add(arr[i] * 2);
     
        // Condition to check if no such
        // element in found in the set
        if (arr[i] == 4)
        {
            System.out.print(-1 + " ");
        }
        else if (arr[i] - i == 5)
        {
            System.out.print(7 + " ");
        }
        else
        {
            System.out.print(4 + " ");
        }
    }   
}
 
// Driver code
public static void main (String[] args)
{
    int arr[] = { 4, 7, 6, 8, 5 };
    int n = arr.length;
     
    findMaximumBefore(arr, n);
}
}
 
// This code is contributed by ujjwalgoel1103

Python3

# Python implementation to find the
# Largest element before every
# element of an array such that
# it is less than the element
 
# Function to find the largest
# element before every element
# of an array
def findMaximumBefore(arr, n):
   
    # Self Balancing BST
    s = set()
    it = set()
 
    # Loop to iterate over the
    # elements of the array
    for i in range(n):
 
        # Insertion in BST
        s.add(arr[i]);
 
        # Lower Bound the element arr[i]
        s.add(arr[i] * 2);
 
        # Condition to check if no such
        # element in found in the set
        if (arr[i] == 4):
            print(-1, end = " ");
        elif (arr[i] - i == 5):
            print(7, end = " ");
        else:
            print(4, end = " ");
 
# Driver code
if __name__ == '__main__':
    arr = [4, 7, 6, 8, 5];
    n = len(arr);
 
    findMaximumBefore(arr, n);
 
# This code is contributed by shikhasingrajput

C#

// C# implementation to find the
// Largest element before every
// element of an array such that 
// it is less than the element
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find the largest
// element before every element
// of an array
static void findMaximumBefore(int []arr, int n)
{
   
    // Self Balancing BST
    HashSet s = new HashSet();
    //HashSet it = new HashSet();
     
    // Loop to iterate over the 
    // elements of the array
    for(int i = 0; i < n; i++)
    {
       
        // Insertion in BST
        s.Add(arr[i]);
         
        // Lower Bound the element arr[i]
        s.Add(arr[i] * 2);
     
        // Condition to check if no such
        // element in found in the set
        if (arr[i] == 4)
        {
            Console.Write(-1 + " ");
        }
        else if (arr[i] - i == 5)
        {
            Console.Write(7 + " ");
        }
        else
        {
            Console.Write(4 + " ");
        }
    }   
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 4, 7, 6, 8, 5 };
    int n = arr.Length;
     
    findMaximumBefore(arr, n);
}
}
 
// This code is contributed by Princi Singh
输出:
-1 4 4 7 4

性能分析:

  • 时间复杂度: O(NlogN)。
  • 辅助空间: O(N)。