📌  相关文章
📜  计算左侧和右侧至少有一个较小元素的数组元素

📅  最后修改于: 2021-05-19 18:52:14             🧑  作者: Mango

给定长度为N的数组arr [] ,任务是查找数组arr []中的元素数量,该数组的左侧右侧至少包含一个较小的元素

例子:

天真的方法:最简单的方法是遍历给定的数组,并为每个元素计算左侧和右侧较小元素的数量。如果两个计数均至少为1 ,则将答案增加1 。最后,打印获得的答案。

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

高效方法:为了优化上述方法,我们的想法是使用堆栈。保持不断增加的元素堆栈,以便在恒定时间内对较小的元素进行计数。请按照以下步骤解决问题:

  • 初始化堆栈,并将变量count设为0,将其作为满足给定条件的数量的计数。
  • 使用变量i遍历给定数组并执行以下步骤:
    • 迭代直到堆栈不为空并且当前元素小于堆栈的顶部元素,然后:
      • 堆栈顶部的元素在右侧具有较小的元素,即arr [i]
      • 如果堆栈大小大于1 ,则左侧还有一个较小的元素,因为堆栈已作为递增堆栈进行维护。
      • 如果以上条件都满足,那么加1计数。
      • 从堆栈中弹出顶部元素。
    • 将当前元素推入堆栈。
  • 完成上述步骤后, count的值即为结果计数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
#include 
using namespace std;
  
// Function to count the number of
// elements that have smaller on
// left and right side
void findElements(int* arr, int N)
{
    // Initialize stack
    stack stack;
  
    // Stores the required count
    // of array elements
    int count = 0;
  
    // Traverse the array A{]
    for (int i = 0; i < N; i++) {
  
        // If stack is not empty
        // and stack top > arr[i]
        while (!stack.empty()
               && arr[i] < stack.top()) {
  
            // If stack size > 1 
            if (stack.size() > 1)
                
                // Increment count
                count++;
  
            // Pop the top element
            stack.pop();
        }
  
        // Push the element arr[i]
        stack.push(arr[i]);
    }
  
    // Print the final count
    cout << count;
}
  
// Driver Code
int main()
{
    int arr[] = { 3, 9, 4, 6, 7, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Function Call
    findElements(arr, N);
  
    return 0;
}


Java
// Java program for the 
// above approach
import java.util.*;
class GFG{
  
// Function to count the number of
// elements that have smaller on
// left and right side
static void findElements(int[] arr,
                         int N)
{
  // Initialize stack
  Stack stack = new Stack<>();
  
  // Stores the required count
  // of array elements
  int count = 0;
  
  // Traverse the array A{]
  for (int i = 0; i < N; i++) 
  {
    // If stack is not empty
    // and stack top > arr[i]
    while (!stack.isEmpty() && 
           arr[i] < stack.peek()) 
    {
      // If stack size > 1 
      if (stack.size() > 1)
  
        // Increment count
        count++;
  
      // Pop the top element
      stack.pop();
    }
  
    // Push the element arr[i]
    stack.add(arr[i]);
  }
  
  // Print the final count
  System.out.print(count);
}
  
// Driver Code
public static void main(String[] args)
{
  int arr[] = {3, 9, 4, 6, 7, 5};
  int N = arr.length;
  
  // Function Call
  findElements(arr, N);
}
}
  
// This code is contributed by shikhasingrajput


Python3
# Python3 program for the above approach
  
# Function to count the number of
# elements that have smaller on
# left and right side
def findElements(arr, N):
      
    # Initialize stack
    stack = []
  
    # Stores the required count
    # of array elements
    count = 0
  
    # Traverse the array A{]
    for i in range(N):
          
        # If stack is not empty
        # and stack top > arr[i]
        while (len(stack) > 0 and 
                   arr[i] < stack[-1]):
  
            # If stack size > 1
            if (len(stack) > 1):
                  
                # Increment count
                count += 1
  
            # Pop the top element
            del stack[-1]
  
        # Push the element arr[i]
        stack.append(arr[i])
  
    # Print the final count
    print(count)
  
# Driver Code
if __name__ == '__main__':
      
    arr = [ 3, 9, 4, 6, 7, 5 ]
    N = len(arr)
  
    # Function Call
    findElements(arr, N)
  
# This code is contributed by mohit kumar 29


C#
// C# program for the 
// above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function to count the number of
// elements that have smaller on
// left and right side
static void findElements(int[] arr, int N)
{
      
    // Initialize stack
    Stack stack = new Stack();
      
    // Stores the required count
    // of array elements
    int count = 0;
      
    // Traverse the array A{]
    for(int i = 0; i < N; i++) 
    {
          
        // If stack is not empty
        // and stack top > arr[i]
        while (stack.Count != 0 && 
               arr[i] < stack.Peek()) 
        {
              
            // If stack size > 1 
            if (stack.Count > 1)
          
                // Increment count
                count++;
          
            // Pop the top element
            stack.Pop();
        }
      
        // Push the element arr[i]
        stack.Push(arr[i]);
    }
      
    // Print the readonly count
    Console.Write(count);
}
  
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 3, 9, 4, 6, 7, 5 };
    int N = arr.Length;
      
    // Function Call
    findElements(arr, N);
}
}
  
// This code is contributed by 29AjayKumar


输出:
3









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