📌  相关文章
📜  arr[i] 是第一个也是最少的每个 Array 元素的子数组计数

📅  最后修改于: 2022-05-13 01:57:09.369000             🧑  作者: Mango

arr[i] 是第一个也是最少的每个 Array 元素的子数组计数

给定一个数组arr[] ,任务是找到从当前元素开始的数组的计数,该当前元素具有最小元素作为当前元素本身。

例子:

幼稚的解决方案:幼稚的方法围绕以下想法:

该任务可以使用2 个循环来解决。外循环一一挑选所有元素。内循环为外循环选取的元素寻找第一个较小的元素。如果找到较小的元素,则将该元素索引-当前索引存储为下一个,否则,存储长度-当前索引

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the count of subarrays
vector countOfSubArray(vector arr)
{
    int next, i, j;
    int n = arr.size();
    vector ans;
 
    for (i = 0; i < n; i++) {
        bool flag = false;
 
        // If the next smaller element
        // is not found then
        // length - current index
        // would be the answer
        next = n - i;
        for (j = i + 1; j < n; j++) {
            if (arr[i] > arr[j]) {
 
                // If the next smaller
                // element is found then
                // the difference of indices
                // will be the count
                next = j - i;
                ans.push_back(next);
                flag = true;
                break;
            }
        }
 
        if (flag == false) {
            ans.push_back(next);
        }
    }
    return ans;
}
 
// Driver Code
int main()
{
    vector arr{ 1, 4, 2, 5, 3 };
 
    vector ans = countOfSubArray(arr);
 
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
 
    return 0;
}


Java
// Java program for the above approach
import java.util.ArrayList;
 
class GFG {
 
  // Function to find the count of subarrays
  static ArrayList countOfSubArray(int[] arr) {
    int next, i, j;
    int n = arr.length;
    ArrayList ans = new ArrayList();
 
    for (i = 0; i < n; i++) {
      boolean flag = false;
 
      // If the next smaller element
      // is not found then
      // length - current index
      // would be the answer
      next = n - i;
      for (j = i + 1; j < n; j++) {
        if (arr[i] > arr[j]) {
 
          // If the next smaller
          // element is found then
          // the difference of indices
          // will be the count
          next = j - i;
          ans.add(next);
          flag = true;
          break;
        }
      }
 
      if (flag == false) {
        ans.add(next);
      }
    }
    return ans;
  }
 
  // Driver Code
  public static void main(String args[])
  {
    int[] arr = { 1, 4, 2, 5, 3 };
    ArrayList ans = countOfSubArray(arr);
 
    for (int i = 0; i < ans.size(); i++) {
      System.out.print(ans.get(i) + " ");
    }
  }
}
 
// This code is contributed by gfgking.


Python3
# Python code for the above approach
 
# Function to find the count of subarrays
def countOfSubArray(arr):
    n = len(arr)
    ans = []
 
    for i in range(n):
        flag = 0
 
        # If the next smaller element
        # is not found then
        # length - current index
        # would be the answer
        next = n - i
        for j in range(i + 1, n):
            if arr[i] > arr[j]:
 
                # If the next smaller
                # element is found then
                # the difference of indices
                # will be the count
                next = j - i
                ans.append(next)
                flag = 1
                break
 
        if flag == 0:
            ans.append(next)
 
    return ans
 
 # Driver Code
arr = [1, 4, 2, 5, 3]
ans = countOfSubArray(arr)
 
for i in range(len(ans)):
    print(ans[i], end = " ")
 
# This code is contributed by Potta Lokesh


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
  // Function to find the count of subarrays
  static List countOfSubArray(int[] arr)
  {
    int next, i, j;
    int n = arr.Length;
    List ans = new List();
 
    for (i = 0; i < n; i++) {
      bool flag = false;
 
      // If the next smaller element
      // is not found then
      // length - current index
      // would be the answer
      next = n - i;
      for (j = i + 1; j < n; j++) {
        if (arr[i] > arr[j]) {
 
          // If the next smaller
          // element is found then
          // the difference of indices
          // will be the count
          next = j - i;
          ans.Add(next);
          flag = true;
          break;
        }
      }
 
      if (flag == false) {
        ans.Add(next);
      }
    }
    return ans;
  }
 
  // Driver Code
  public static void Main()
  {
    int[] arr = { 1, 4, 2, 5, 3 };
    List ans = countOfSubArray(arr);
 
    for (int i = 0; i < ans.Count; i++) {
      Console.Write(ans[i] + " ");
    }
  }
}
 
// This code is contributed by ukasp.


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to determine how many count
// of subarrays are possible
// with each number
vector countOfSubArray(vector arr)
{
 
    stack st;
    // To store the answer
    vector v;
    int n = arr.size();
 
    // Traverse all the numbers
    for (int i = n - 1; i >= 0; i--) {
 
        // Check if current index is the
        // next smaller element of
        // any previous indices
        while (st.size() > 0
               && arr[st.top()] >= arr[i]) {
            // Pop the element
            st.pop();
        }
 
        if (st.size() == 0) {
            v.push_back(n - i);
        }
        else {
            v.push_back(st.top() - i);
        }
 
        // Push the current index
        st.push(i);
    }
    // reverse the output
    reverse(v.begin(), v.end());
    return v;
}
 
// Driver Code
int main()
{
    // Given numbers
    vector arr{ 1, 4, 2, 5, 3 };
 
    // Function Call
    vector ans = countOfSubArray(arr);
 
    // Printing the result
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
// Function to determine how many count
// of subarrays are possible
// with each number
static Vector countOfSubArray(int[] arr)
{
 
    Stack st = new Stack();
   
    // To store the answer
    Vector v = new Vector();
    int n = arr.length;
 
    // Traverse all the numbers
    for (int i = n - 1; i >= 0; i--) {
 
        // Check if current index is the
        // next smaller element of
        // any previous indices
        while (st.size() > 0
               && arr[st.peek()] >= arr[i])
        {
           
            // Pop the element
            st.pop();
        }
 
        if (st.size() == 0) {
            v.add(n - i);
        }
        else {
            v.add(st.peek() - i);
        }
 
        // Push the current index
        st.add(i);
    }
   
    // reverse the output
    Collections.reverse(v);
    return v;
}
 
// Driver Code
public static void main(String[] args)
{
   
    // Given numbers
    int []arr ={ 1, 4, 2, 5, 3 };
 
    // Function Call
    Vector ans = countOfSubArray(arr);
 
    // Printing the result
    for (int i = 0; i < ans.size(); i++) {
        System.out.print(ans.get(i)+ " ");
    }
 
}
}
 
// This code is contributed by shikhasingrajput


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function to determine how many count
  // of subarrays are possible
  // with each number
  static List countOfSubArray(int[] arr)
  {
 
    Stack st = new Stack();
 
    // To store the answer
    List v = new List();
    int n = arr.Length;
 
    // Traverse all the numbers
    for (int i = n - 1; i >= 0; i--) {
 
      // Check if current index is the
      // next smaller element of
      // any previous indices
      while (st.Count > 0
             && arr[st.Peek()] >= arr[i])
      {
 
        // Pop the element
        st.Pop();
      }
 
      if (st.Count == 0) {
        v.Add(n - i);
      }
      else {
        v.Add(st.Peek() - i);
      }
 
      // Push the current index
      st.Push(i);
    }
 
    // reverse the output
    v.Reverse();
    return v;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
 
    // Given numbers
    int []arr ={ 1, 4, 2, 5, 3 };
 
    // Function Call
    List ans = countOfSubArray(arr);
 
    // Printing the result
    for (int i = 0; i < ans.Count; i++) {
      Console.Write(ans[i]+ " ");
    }
  }
}
 
// This code is contributed by 29AjayKumar



输出
5 1 3 1 1 

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

高效解法:这个问题主要是求当前索引从下一个较小数字的索引到当前索引处的数字有多远。解决此问题的最佳方法是使用堆栈
请按照以下步骤解决问题:

  • 使用当前索引遍历给定数组 arr[] 的每个数字。
  • 如果堆栈为空,则将当前索引压入堆栈。
  • 如果堆栈不为空,则执行以下操作:
    • 如果当前索引处的编号小于栈顶索引的编号,则压入当前索引。
    • 如果当前索引处的个数大于栈顶索引的个数,则更新子数组的计数为栈顶索引——当前索引
  • 一旦在输出列表中更新了天数,就弹出堆栈。
  • 对堆栈中大于当前索引处的数字的所有索引重复上述步骤。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to determine how many count
// of subarrays are possible
// with each number
vector countOfSubArray(vector arr)
{
 
    stack st;
    // To store the answer
    vector v;
    int n = arr.size();
 
    // Traverse all the numbers
    for (int i = n - 1; i >= 0; i--) {
 
        // Check if current index is the
        // next smaller element of
        // any previous indices
        while (st.size() > 0
               && arr[st.top()] >= arr[i]) {
            // Pop the element
            st.pop();
        }
 
        if (st.size() == 0) {
            v.push_back(n - i);
        }
        else {
            v.push_back(st.top() - i);
        }
 
        // Push the current index
        st.push(i);
    }
    // reverse the output
    reverse(v.begin(), v.end());
    return v;
}
 
// Driver Code
int main()
{
    // Given numbers
    vector arr{ 1, 4, 2, 5, 3 };
 
    // Function Call
    vector ans = countOfSubArray(arr);
 
    // Printing the result
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
class GFG{
 
// Function to determine how many count
// of subarrays are possible
// with each number
static Vector countOfSubArray(int[] arr)
{
 
    Stack st = new Stack();
   
    // To store the answer
    Vector v = new Vector();
    int n = arr.length;
 
    // Traverse all the numbers
    for (int i = n - 1; i >= 0; i--) {
 
        // Check if current index is the
        // next smaller element of
        // any previous indices
        while (st.size() > 0
               && arr[st.peek()] >= arr[i])
        {
           
            // Pop the element
            st.pop();
        }
 
        if (st.size() == 0) {
            v.add(n - i);
        }
        else {
            v.add(st.peek() - i);
        }
 
        // Push the current index
        st.add(i);
    }
   
    // reverse the output
    Collections.reverse(v);
    return v;
}
 
// Driver Code
public static void main(String[] args)
{
   
    // Given numbers
    int []arr ={ 1, 4, 2, 5, 3 };
 
    // Function Call
    Vector ans = countOfSubArray(arr);
 
    // Printing the result
    for (int i = 0; i < ans.size(); i++) {
        System.out.print(ans.get(i)+ " ");
    }
 
}
}
 
// This code is contributed by shikhasingrajput

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function to determine how many count
  // of subarrays are possible
  // with each number
  static List countOfSubArray(int[] arr)
  {
 
    Stack st = new Stack();
 
    // To store the answer
    List v = new List();
    int n = arr.Length;
 
    // Traverse all the numbers
    for (int i = n - 1; i >= 0; i--) {
 
      // Check if current index is the
      // next smaller element of
      // any previous indices
      while (st.Count > 0
             && arr[st.Peek()] >= arr[i])
      {
 
        // Pop the element
        st.Pop();
      }
 
      if (st.Count == 0) {
        v.Add(n - i);
      }
      else {
        v.Add(st.Peek() - i);
      }
 
      // Push the current index
      st.Push(i);
    }
 
    // reverse the output
    v.Reverse();
    return v;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
 
    // Given numbers
    int []arr ={ 1, 4, 2, 5, 3 };
 
    // Function Call
    List ans = countOfSubArray(arr);
 
    // Printing the result
    for (int i = 0; i < ans.Count; i++) {
      Console.Write(ans[i]+ " ");
    }
  }
}
 
// This code is contributed by 29AjayKumar


输出
5 1 3 1 1 

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