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

📅  最后修改于: 2021-09-03 03:21:25             🧑  作者: Mango

给定的阵列ARR []的长度N,所述任务是找到在阵列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


Javascript


输出:
3

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live