📌  相关文章
📜  所有可能长度的每个子数组中存在的最小元素

📅  最后修改于: 2021-05-06 08:28:44             🧑  作者: Mango

给定长度为N的数组arr [] ,子数组每个可能长度的任务是找到该长度的每个子数组中存在的最小元素。

例子:

原始的方法:我们的想法是找到在大小为K的所有子阵列的共同的元素为K(1≤ķ≤N)的每个可能值,并打印的最小共同元件。请按照以下步骤解决问题:

  1. 将长度为K的每个子数组的每个唯一数的计数相加。
  2. 检查数字的数量是否等于子数组的数量,即N – K – 1
  3. 如果发现是真的,则该特定元素出现在大小为K的每个子数组中。
  4. 对于多个此类元素,请打印其中最小的元素。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to add count of numbers
// in the map for a subarray of length k
void uniqueElements(int arr[], int start, int K,
                    map& mp)
{
    // Set to store unique elements
    set st;
 
    // Add elements to the set
    for (int i = 0; i < K; i++)
        st.insert(arr[start + i]);
 
    // Iterator of the set
    set::iterator itr = st.begin();
 
    // Adding count in map
    for (; itr != st.end(); itr++)
        mp[*itr]++;
}
 
// Funtion to check if there is any number
// which repeats itself in every subarray
// of length K
void checkAnswer(map& mp, int N, int K)
{
    // Check all number starting from 1
    for (int i = 1; i <= N; i++) {
 
        // Check if i occured n-k+1 times
        if (mp[i] == (N - K + 1)) {
 
            // Print the smallest number
            cout << i << " ";
            return;
        }
    }
 
    // Print -1, if no such number found
    cout << -1 << " ";
}
 
// Function to count frequency of each
// number in each subarray of length K
void smallestPresentNumber(int arr[], int N, int K)
{
    map mp;
 
    // Traverse all subarrays of length K
    for (int i = 0; i <= N - K; i++) {
        uniqueElements(arr, i, K, mp);
    }
 
    // Check and print the smallest number
    // present in every subarray and print it
    checkAnswer(mp, N, K);
}
 
// Function to generate the value of K
void generateK(int arr[], int N)
{
    for (int k = 1; k <= N; k++)
 
        // Functoin call
        smallestPresentNumber(arr, N, k);
}
 
// Driver Code
int main()
{
 
    // Given array
    int arr[] = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
 
    // Size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    generateK(arr, N);
 
    return (0);
}


Java
// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG
{
 
  // Function to add count of numbers
  // in the map for a subarray of length k
  static void uniqueElements(int arr[], int start, int K,
                             Map mp)
  {
    // Set to store unique elements
    Set st=new HashSet<>();
 
    // Add elements to the set
    for (int i = 0; i < K; i++)
      st.add(arr[start + i]);
 
    // Iterator of the set
    Iterator itr = st.iterator();
 
    // Adding count in map
    while(itr.hasNext())
    {
      Integer t = (Integer)itr.next();
      mp.put(t,mp.getOrDefault(t, 0) + 1);
    }
 
  }
 
  // Funtion to check if there is any number
  // which repeats itself in every subarray
  // of length K
  static void checkAnswer(Map mp, int N, int K)
  {
 
    // Check all number starting from 1
    for (int i = 1; i <= N; i++)
    {
 
      // Check if i occured n-k+1 times
      if(mp.containsKey(i))   
        if (mp.get(i) == (N - K + 1))
        {
 
          // Print the smallest number
          System.out.print(i + " ");
          return;
        }
    }
 
    // Print -1, if no such number found
    System.out.print(-1 + " ");
  }
 
  // Function to count frequency of each
  // number in each subarray of length K
  static void smallestPresentNumber(int arr[], int N, int K)
  {
    Map mp = new HashMap<>();
 
    // Traverse all subarrays of length K
    for (int i = 0; i <= N - K; i++)
    {
      uniqueElements(arr, i, K, mp);
    }
 
    // Check and print the smallest number
    // present in every subarray and print it
    checkAnswer(mp, N, K);
  }
 
  // Function to generate the value of K
  static void generateK(int arr[], int N)
  {
    for (int k = 1; k <= N; k++)
 
      // Functoin call
      smallestPresentNumber(arr, N, k);
  }
 
  // Driver code
  public static void main (String[] args)
  {
    // Given array
    int arr[] = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
 
    // Size of array
    int N = arr.length;
 
    // Function call
    generateK(arr, N);
 
  }
}
 
// This code is contributed by offbeat.


Python3
# Python3 program for the above approach
 
# Function to add count of numbers
# in the map for a subarray of length k
def uniqueElements(arr, start, K, mp) :
 
    # Set to store unique elements
    st = set();
 
    # Add elements to the set
    for i in range(K) :
        st.add(arr[start + i]);
 
    # Adding count in map
    for itr in st:
        if itr in mp :
            mp[itr] += 1;
        else:
            mp[itr] = 1;
 
# Funtion to check if there is any number
# which repeats itself in every subarray
# of length K
def checkAnswer(mp, N, K) :
 
    # Check all number starting from 1
    for i in range(1, N + 1) :
         
        if i in mp :
           
            # Check if i occured n-k+1 times
            if (mp[i] == (N - K + 1)) :
     
                # Print the smallest number
                print(i, end = " ");
                return;
 
    # Print -1, if no such number found
    print(-1, end = " ");
 
# Function to count frequency of each
# number in each subarray of length K
def smallestPresentNumber(arr, N,  K) :
    mp = {};
 
    # Traverse all subarrays of length K
    for i in range(N - K + 1) :
        uniqueElements(arr, i, K, mp);
 
    # Check and print the smallest number
    # present in every subarray and print it
    checkAnswer(mp, N, K);
 
# Function to generate the value of K
def generateK(arr, N) :
 
    for k in range(1, N + 1) :
 
        # Functoin call
        smallestPresentNumber(arr, N, k);
 
# Driver Code
if __name__ == "__main__" :
 
    # Given array
    arr = [ 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 ];
 
    # Size of array
    N = len(arr);
 
    # Function call
    generateK(arr, N);
     
    # This code is contributed by AnkThon


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to add count of numbers
  // in the map for a subarray of length k
  static void uniqueElements(int[] arr, int start,
                             int K, Dictionary mp)
  {
 
    // Set to store unique elements
    HashSet st = new HashSet();
 
    // Add elements to the set
    for (int i = 0; i < K; i++)
      st.Add(arr[start + i]);
 
    // Adding count in map
    foreach(int itr in st)
    {
      if(mp.ContainsKey(itr))
      {
        mp[itr]++;
      }
      else{
        mp[itr] = 1;
      }
    }
  }
 
  // Funtion to check if there is any number
  // which repeats itself in every subarray
  // of length K
  static void checkAnswer(Dictionary mp, int N, int K)
  {
 
    // Check all number starting from 1
    for (int i = 1; i <= N; i++)
    {
 
      // Check if i occured n-k+1 times
      if(mp.ContainsKey(i))   
        if (mp[i] == (N - K + 1))
        {
 
          // Print the smallest number
          Console.Write(i + " ");
          return;
        }
    }
 
    // Print -1, if no such number found
    Console.Write(-1 + " ");
  }
 
  // Function to count frequency of each
  // number in each subarray of length K
  static void smallestPresentNumber(int[] arr, int N, int K)
  {
    Dictionary mp = new Dictionary();
 
    // Traverse all subarrays of length K
    for (int i = 0; i <= N - K; i++)
    {
      uniqueElements(arr, i, K, mp);
    }
 
    // Check and print the smallest number
    // present in every subarray and print it
    checkAnswer(mp, N, K);
  }
 
  // Function to generate the value of K
  static void generateK(int[] arr, int N)
  {
    for (int k = 1; k <= N; k++)
 
      // Functoin call
      smallestPresentNumber(arr, N, k);
  }
 
  // Driver code
  static void Main()
  {
 
    // Given array
    int[] arr = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
 
    // Size of array
    int N = arr.Length;
 
    // Function call
    generateK(arr, N);
  }
}
 
// This code is contributed by divyesh072019.


C++
// C++ program of the above approach
 
#include 
using namespace std;
 
// Function to print the common
// elements for all subarray lengths
void printAnswer(int answer[], int N)
{
    for (int i = 1; i <= N; i++) {
        cout << answer[i] << " ";
    }
}
 
// Function to find and store the
// minimum element present in all
// subarrays of all lengths from 1 to n
void updateAnswerArray(int answer[], int N)
{
    int i = 0;
 
    // Skip lengths for which
    // answer[i] is -1
    while (answer[i] == -1)
        i++;
 
    // Initialize minimum as the first
    // element where answer[i] is not -1
    int minimum = answer[i];
 
    // Updating the answer array
    while (i <= N) {
 
        // If answer[i] is -1, then minimum
        // can be substituted in that place
        if (answer[i] == -1)
            answer[i] = minimum;
 
        // Find minimum answer
        else
            answer[i] = min(minimum, answer[i]);
        minimum = min(minimum, answer[i]);
        i++;
    }
}
 
// Function to find the minimum number
// corresponding to every subarray of
// length K, for every K from 1 to N
void lengthOfSubarray(vector indices[],
                      set st, int N)
{
    // Stores the minimum common
    // elements for all subarray lengths
    int answer[N + 1];
 
    // Initialize with -1.
    memset(answer, -1, sizeof(answer));
 
    // Find for every element, the minimum length
    // such that the number is present in every
    // subsequence of that particular length or more
    for (auto itr : st) {
 
        // To store first occurence and
        // gaps between occurences
        int start = -1;
        int gap = -1;
 
        // To cover the distance between last
        // occurence and the end of the array
        indices[itr].push_back(N);
 
        // To find the distance
        // between any two occurences
        for (int i = 0; i < indices[itr].size(); i++) {
            gap = max(gap, indices[itr][i] - start);
            start = indices[itr][i];
        }
        if (answer[gap] == -1)
            answer[gap] = itr;
    }
 
    // Update and store the answer
    updateAnswerArray(answer, N);
 
    // Print the required answer
    printAnswer(answer, N);
}
 
// Function to find the smallest
// element common in all subarrays for
// every possible subarray lengths
void smallestPresentNumber(int arr[], int N)
{
    // Initializing indices array
    vector indices[N + 1];
 
    // Store the numbers present
    // in the array
    set elements;
 
    // Push the index in the indices[A[i]] and
    // also store the numbers in set to get
    // the numbers present in input array
    for (int i = 0; i < N; i++) {
        indices[arr[i]].push_back(i);
        elements.insert(arr[i]);
    }
 
    // Function call to calculate length of
    // subarray for which a number is present
    // in every subarray of that length
    lengthOfSubarray(indices, elements, N);
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
 
    // Size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    smallestPresentNumber(arr, N);
 
    return (0);
}


Java
// Java program for above approach
import java.util.*;
import java.lang.*;
 
class GFG
{
 
  // Function to print the common
  // elements for all subarray lengths
  static void printAnswer(int answer[], int N)
  {
    for (int i = 1; i <= N; i++)
    {
      System.out.print(answer[i]+" ");
    }
  }
 
  // Function to find and store the
  // minimum element present in all
  // subarrays of all lengths from 1 to n
  static void updateAnswerArray(int answer[], int N)
  {
    int i = 0;
 
    // Skip lengths for which
    // answer[i] is -1
    while (answer[i] == -1)
      i++;
 
    // Initialize minimum as the first
    // element where answer[i] is not -1
    int minimum = answer[i];
 
    // Updating the answer array
    while (i <= N) {
 
      // If answer[i] is -1, then minimum
      // can be substituted in that place
      if (answer[i] == -1)
        answer[i] = minimum;
 
      // Find minimum answer
      else
        answer[i] = Math.min(minimum, answer[i]);
      minimum = Math.min(minimum, answer[i]);
      i++;
    }
  }
 
  // Function to find the minimum number
  // corresponding to every subarray of
  // length K, for every K from 1 to N
  static void lengthOfSubarray(ArrayList> indices,
                               Set st, int N)
  {
    // Stores the minimum common
    // elements for all subarray lengths
    int[] answer = new int[N + 1];
 
    // Initialize with -1.
    Arrays.fill(answer, -1);
 
    // Find for every element, the minimum length
    // such that the number is present in every
    // subsequence of that particular length or more
    Iterator itr = st.iterator();
    while (itr.hasNext())
    {
 
      // To store first occurence and
      // gaps between occurences
      int start = -1;
      int gap = -1;
      int t = (int)itr.next();
 
      // To cover the distance between last
      // occurence and the end of the array
      indices.get(t).add(N);
 
      // To find the distance
      // between any two occurences
      for (int i = 0; i < indices.get(t).size(); i++)
      {
        gap = Math.max(gap, indices.get(t).get(i) - start);
        start = indices.get(t).get(i);
      }
      if (answer[gap] == -1)
        answer[gap] = t;
    }
 
    // Update and store the answer
    updateAnswerArray(answer, N);
 
    // Print the required answer
    printAnswer(answer, N);
  }
 
  // Function to find the smallest
  // element common in all subarrays for
  // every possible subarray lengths
  static void smallestPresentNumber(int arr[], int N)
  {
    // Initializing indices array
    ArrayList> indices = new ArrayList<>();
 
    for(int i = 0; i <= N; i++)
      indices.add(new ArrayList());
 
    // Store the numbers present
    // in the array
    Set elements = new HashSet<>();
 
    // Push the index in the indices[A[i]] and
    // also store the numbers in set to get
    // the numbers present in input array
    for (int i = 0; i < N; i++)
    {
      indices.get(arr[i]).add(i);
      elements.add(arr[i]);
    }
 
    // Function call to calculate length of
    // subarray for which a number is present
    // in every subarray of that length
    lengthOfSubarray(indices, elements, N);
  }
 
  // Driver function
  public static void main (String[] args)
  {
 
    // Given array
    int arr[] = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
 
    // Size of array
    int N = arr.length;
 
    // Function Call
    smallestPresentNumber(arr, N);
  }
}
 
// This code is contributed by offbeat


C#
// C# program for above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to print the common
// elements for all subarray lengths
static void printAnswer(int[] answer, int N)
{
    for(int i = 1; i <= N; i++)
    {
        Console.Write(answer[i] + " ");
    }
}
 
// Function to find and store the
// minimum element present in all
// subarrays of all lengths from 1 to n
static void updateAnswerArray(int[] answer, int N)
{
    int i = 0;
     
    // Skip lengths for which
    // answer[i] is -1
    while (answer[i] == -1)
        i++;
     
    // Initialize minimum as the first
    // element where answer[i] is not -1
    int minimum = answer[i];
     
    // Updating the answer array
    while (i <= N)
    {
         
        // If answer[i] is -1, then minimum
        // can be substituted in that place
        if (answer[i] == -1)
            answer[i] = minimum;
         
        // Find minimum answer
        else
            answer[i] = Math.Min(minimum, answer[i]);
            minimum = Math.Min(minimum, answer[i]);
            i++;
    }
}
 
// Function to find the minimum number
// corresponding to every subarray of
// length K, for every K from 1 to N
static void lengthOfSubarray(List> indices,
                               HashSet st, int N)
{
    // Stores the minimum common
    // elements for all subarray lengths
    int[] answer = new int[N + 1];
     
    // Initialize with -1.
    Array.Fill(answer, -1);
     
    // Find for every element, the minimum length
    // such that the number is present in every
    // subsequence of that particular length or more
    foreach(int itr in st)
    {
         
        // To store first occurence and
        // gaps between occurences
        int start = -1;
        int gap = -1;
        int t = itr;
         
        // To cover the distance between last
        // occurence and the end of the array
        indices[t].Add(N);
         
        // To find the distance
        // between any two occurences
        for(int i = 0; i < indices[t].Count; i++)
        {
            gap = Math.Max(gap, indices[t][i] - start);
            start = indices[t][i];
        }
        if (answer[gap] == -1)
            answer[gap] = t;
    }
     
    // Update and store the answer
    updateAnswerArray(answer, N);
     
    // Print the required answer
    printAnswer(answer, N);
}
 
// Function to find the smallest
// element common in all subarrays for
// every possible subarray lengths
static void smallestPresentNumber(int[] arr, int N)
{
     
    // Initializing indices array
    List> indices = new List>();
     
    for(int i = 0; i <= N; i++)
        indices.Add(new List());
     
    // Store the numbers present
    // in the array
    HashSet elements = new HashSet();
     
    // Push the index in the indices[A[i]] and
    // also store the numbers in set to get
    // the numbers present in input array
    for(int i = 0; i < N; i++)
    {
        indices[arr[i]].Add(i);
        elements.Add(arr[i]);
    }
     
    // Function call to calculate length of
    // subarray for which a number is present
    // in every subarray of that length
    lengthOfSubarray(indices, elements, N);
}
 
// Driver code
static void Main()
{
     
    // Given array
    int[] arr = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
     
    // Size of array
    int N = arr.Length;
     
    // Function Call
    smallestPresentNumber(arr, N);
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python program of the above approach
 
# Function to print the common
# elements for all subarray lengths
def printAnswer(answer, N):
    for i in range(N + 1):
        print(answer[i], end = " ")
 
# Function to find and store the
# minimum element present in all
# subarrays of all lengths from 1 to n
def updateAnswerArray(answer, N):
    i = 0
     
    # Skip lengths for which
    # answer[i] is -1
    while(answer[i] == -1):
        i += 1
     
    # Initialize minimum as the first
    # element where answer[i] is not -1
    minimum = answer[i]
     
    # Updating the answer array
    while(i <= N):
         
        # If answer[i] is -1, then minimum
        # can be substituted in that place
        if(answer[i] == -1):
            answer[i] = minimum
         
        # Find minimum answer
        else:
            answer[i] = min(minimum, answer[i])
        minimum = min(minimum, answer[i])
        i += 1
 
# Function to find the minimum number
# corresponding to every subarray of
# length K, for every K from 1 to N
def lengthOfSubarray(indices, st, N):
     
    # Stores the minimum common
    # elements for all subarray lengths
    #Initialize with -1.
    answer = [-1 for i in range(N + 1)]
     
    # Find for every element, the minimum length
    # such that the number is present in every
    # subsequence of that particular length or more
    for itr in st:
         
        # To store first occurence and
        # gaps between occurences
        start = -1
        gap = -1
         
        # To cover the distance between last
        # occurence and the end of the array
        indices[itr].append(N)
         
        # To find the distance
        # between any two occurences
        for i in range(len(indices[itr])):
            gap = max(gap, indices[itr][i] - start)
            start = indices[itr][i]
         
        if(answer[gap] == -1):
            answer[gap] = itr
     
    # Update and store the answer
    updateAnswerArray(answer, N)
     
    # Print the required answer
    printAnswer(answer, N)
     
# Function to find the smallest
# element common in all subarrays for
# every possible subarray lengths
def smallestPresentNumber(arr, N):
     
    # Initializing indices array
    indices = [[] for i in range(N + 1)]
     
    # Store the numbers present
    # in the array
    elements = []
     
    # Push the index in the indices[A[i]] and
    # also store the numbers in set to get
    # the numbers present in input array
    for i in range(N):
        indices[arr[i]].append(i)
        elements.append(arr[i])
     
    elements = list(set(elements))
     
    # Function call to calculate length of
    # subarray for which a number is present
    # in every subarray of that length
    lengthOfSubarray(indices, elements, N)
 
# Driver Code
 
# Given array
arr = [2, 3, 5, 3, 2, 3, 1, 3, 2, 7]
 
# Size of array
N = len(arr)
 
# Function Call
smallestPresentNumber(arr, N)
 
# This code is contributed by avanitrachhadiya2155


输出:
-1 -1 3 2 2 2 1 1 1 1

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

高效方法:如果所有其中所述特定数目是存在于阵列中的索引使用数组存储和找到的最小长度,使得其存在于长度为1的每子阵列≤ķ≤n中的上述方法可以被优化。

请按照以下步骤解决问题:

  1. 初始化一个数组,例如indexs [] ,以在对应于该索引号的特定数字出现的地方存储索引。
  2. 现在,对于给定数组中存在的每个数字,找到最小长度,以使其存在于该长度的每个子数组中。
  3. 最小长度可以通过找到特定编号在给定数组中重复自身的最大间隔来找到。同样,对于其他编号的数组也要查找相同的内容。
  4. -1初始化大小为N + 1answer []数组,其中answer [i]表示长度为K的子数组的答案。
  5. 现在, indexs []数组给出存在于每个长度子数组中的数字,例如K ,然后如果answer [K]-1 ,则用相同的数字更新answer [K]
  6. 遍历之后,更新answer []数组,使得如果在长度为K的所有子数组中都存在一个数字,则该特定数字也将在长度大于K的所有子数组中也存在。
  7. 更新answer []数组后,将该数组中存在的所有元素打印为长度为K的每个子数组的答案。

下面是上述方法的实现:

C++

// C++ program of the above approach
 
#include 
using namespace std;
 
// Function to print the common
// elements for all subarray lengths
void printAnswer(int answer[], int N)
{
    for (int i = 1; i <= N; i++) {
        cout << answer[i] << " ";
    }
}
 
// Function to find and store the
// minimum element present in all
// subarrays of all lengths from 1 to n
void updateAnswerArray(int answer[], int N)
{
    int i = 0;
 
    // Skip lengths for which
    // answer[i] is -1
    while (answer[i] == -1)
        i++;
 
    // Initialize minimum as the first
    // element where answer[i] is not -1
    int minimum = answer[i];
 
    // Updating the answer array
    while (i <= N) {
 
        // If answer[i] is -1, then minimum
        // can be substituted in that place
        if (answer[i] == -1)
            answer[i] = minimum;
 
        // Find minimum answer
        else
            answer[i] = min(minimum, answer[i]);
        minimum = min(minimum, answer[i]);
        i++;
    }
}
 
// Function to find the minimum number
// corresponding to every subarray of
// length K, for every K from 1 to N
void lengthOfSubarray(vector indices[],
                      set st, int N)
{
    // Stores the minimum common
    // elements for all subarray lengths
    int answer[N + 1];
 
    // Initialize with -1.
    memset(answer, -1, sizeof(answer));
 
    // Find for every element, the minimum length
    // such that the number is present in every
    // subsequence of that particular length or more
    for (auto itr : st) {
 
        // To store first occurence and
        // gaps between occurences
        int start = -1;
        int gap = -1;
 
        // To cover the distance between last
        // occurence and the end of the array
        indices[itr].push_back(N);
 
        // To find the distance
        // between any two occurences
        for (int i = 0; i < indices[itr].size(); i++) {
            gap = max(gap, indices[itr][i] - start);
            start = indices[itr][i];
        }
        if (answer[gap] == -1)
            answer[gap] = itr;
    }
 
    // Update and store the answer
    updateAnswerArray(answer, N);
 
    // Print the required answer
    printAnswer(answer, N);
}
 
// Function to find the smallest
// element common in all subarrays for
// every possible subarray lengths
void smallestPresentNumber(int arr[], int N)
{
    // Initializing indices array
    vector indices[N + 1];
 
    // Store the numbers present
    // in the array
    set elements;
 
    // Push the index in the indices[A[i]] and
    // also store the numbers in set to get
    // the numbers present in input array
    for (int i = 0; i < N; i++) {
        indices[arr[i]].push_back(i);
        elements.insert(arr[i]);
    }
 
    // Function call to calculate length of
    // subarray for which a number is present
    // in every subarray of that length
    lengthOfSubarray(indices, elements, N);
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
 
    // Size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    smallestPresentNumber(arr, N);
 
    return (0);
}

Java

// Java program for above approach
import java.util.*;
import java.lang.*;
 
class GFG
{
 
  // Function to print the common
  // elements for all subarray lengths
  static void printAnswer(int answer[], int N)
  {
    for (int i = 1; i <= N; i++)
    {
      System.out.print(answer[i]+" ");
    }
  }
 
  // Function to find and store the
  // minimum element present in all
  // subarrays of all lengths from 1 to n
  static void updateAnswerArray(int answer[], int N)
  {
    int i = 0;
 
    // Skip lengths for which
    // answer[i] is -1
    while (answer[i] == -1)
      i++;
 
    // Initialize minimum as the first
    // element where answer[i] is not -1
    int minimum = answer[i];
 
    // Updating the answer array
    while (i <= N) {
 
      // If answer[i] is -1, then minimum
      // can be substituted in that place
      if (answer[i] == -1)
        answer[i] = minimum;
 
      // Find minimum answer
      else
        answer[i] = Math.min(minimum, answer[i]);
      minimum = Math.min(minimum, answer[i]);
      i++;
    }
  }
 
  // Function to find the minimum number
  // corresponding to every subarray of
  // length K, for every K from 1 to N
  static void lengthOfSubarray(ArrayList> indices,
                               Set st, int N)
  {
    // Stores the minimum common
    // elements for all subarray lengths
    int[] answer = new int[N + 1];
 
    // Initialize with -1.
    Arrays.fill(answer, -1);
 
    // Find for every element, the minimum length
    // such that the number is present in every
    // subsequence of that particular length or more
    Iterator itr = st.iterator();
    while (itr.hasNext())
    {
 
      // To store first occurence and
      // gaps between occurences
      int start = -1;
      int gap = -1;
      int t = (int)itr.next();
 
      // To cover the distance between last
      // occurence and the end of the array
      indices.get(t).add(N);
 
      // To find the distance
      // between any two occurences
      for (int i = 0; i < indices.get(t).size(); i++)
      {
        gap = Math.max(gap, indices.get(t).get(i) - start);
        start = indices.get(t).get(i);
      }
      if (answer[gap] == -1)
        answer[gap] = t;
    }
 
    // Update and store the answer
    updateAnswerArray(answer, N);
 
    // Print the required answer
    printAnswer(answer, N);
  }
 
  // Function to find the smallest
  // element common in all subarrays for
  // every possible subarray lengths
  static void smallestPresentNumber(int arr[], int N)
  {
    // Initializing indices array
    ArrayList> indices = new ArrayList<>();
 
    for(int i = 0; i <= N; i++)
      indices.add(new ArrayList());
 
    // Store the numbers present
    // in the array
    Set elements = new HashSet<>();
 
    // Push the index in the indices[A[i]] and
    // also store the numbers in set to get
    // the numbers present in input array
    for (int i = 0; i < N; i++)
    {
      indices.get(arr[i]).add(i);
      elements.add(arr[i]);
    }
 
    // Function call to calculate length of
    // subarray for which a number is present
    // in every subarray of that length
    lengthOfSubarray(indices, elements, N);
  }
 
  // Driver function
  public static void main (String[] args)
  {
 
    // Given array
    int arr[] = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
 
    // Size of array
    int N = arr.length;
 
    // Function Call
    smallestPresentNumber(arr, N);
  }
}
 
// This code is contributed by offbeat

C#

// C# program for above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to print the common
// elements for all subarray lengths
static void printAnswer(int[] answer, int N)
{
    for(int i = 1; i <= N; i++)
    {
        Console.Write(answer[i] + " ");
    }
}
 
// Function to find and store the
// minimum element present in all
// subarrays of all lengths from 1 to n
static void updateAnswerArray(int[] answer, int N)
{
    int i = 0;
     
    // Skip lengths for which
    // answer[i] is -1
    while (answer[i] == -1)
        i++;
     
    // Initialize minimum as the first
    // element where answer[i] is not -1
    int minimum = answer[i];
     
    // Updating the answer array
    while (i <= N)
    {
         
        // If answer[i] is -1, then minimum
        // can be substituted in that place
        if (answer[i] == -1)
            answer[i] = minimum;
         
        // Find minimum answer
        else
            answer[i] = Math.Min(minimum, answer[i]);
            minimum = Math.Min(minimum, answer[i]);
            i++;
    }
}
 
// Function to find the minimum number
// corresponding to every subarray of
// length K, for every K from 1 to N
static void lengthOfSubarray(List> indices,
                               HashSet st, int N)
{
    // Stores the minimum common
    // elements for all subarray lengths
    int[] answer = new int[N + 1];
     
    // Initialize with -1.
    Array.Fill(answer, -1);
     
    // Find for every element, the minimum length
    // such that the number is present in every
    // subsequence of that particular length or more
    foreach(int itr in st)
    {
         
        // To store first occurence and
        // gaps between occurences
        int start = -1;
        int gap = -1;
        int t = itr;
         
        // To cover the distance between last
        // occurence and the end of the array
        indices[t].Add(N);
         
        // To find the distance
        // between any two occurences
        for(int i = 0; i < indices[t].Count; i++)
        {
            gap = Math.Max(gap, indices[t][i] - start);
            start = indices[t][i];
        }
        if (answer[gap] == -1)
            answer[gap] = t;
    }
     
    // Update and store the answer
    updateAnswerArray(answer, N);
     
    // Print the required answer
    printAnswer(answer, N);
}
 
// Function to find the smallest
// element common in all subarrays for
// every possible subarray lengths
static void smallestPresentNumber(int[] arr, int N)
{
     
    // Initializing indices array
    List> indices = new List>();
     
    for(int i = 0; i <= N; i++)
        indices.Add(new List());
     
    // Store the numbers present
    // in the array
    HashSet elements = new HashSet();
     
    // Push the index in the indices[A[i]] and
    // also store the numbers in set to get
    // the numbers present in input array
    for(int i = 0; i < N; i++)
    {
        indices[arr[i]].Add(i);
        elements.Add(arr[i]);
    }
     
    // Function call to calculate length of
    // subarray for which a number is present
    // in every subarray of that length
    lengthOfSubarray(indices, elements, N);
}
 
// Driver code
static void Main()
{
     
    // Given array
    int[] arr = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
     
    // Size of array
    int N = arr.Length;
     
    // Function Call
    smallestPresentNumber(arr, N);
}
}
 
// This code is contributed by divyeshrabadiya07

Python3

# Python program of the above approach
 
# Function to print the common
# elements for all subarray lengths
def printAnswer(answer, N):
    for i in range(N + 1):
        print(answer[i], end = " ")
 
# Function to find and store the
# minimum element present in all
# subarrays of all lengths from 1 to n
def updateAnswerArray(answer, N):
    i = 0
     
    # Skip lengths for which
    # answer[i] is -1
    while(answer[i] == -1):
        i += 1
     
    # Initialize minimum as the first
    # element where answer[i] is not -1
    minimum = answer[i]
     
    # Updating the answer array
    while(i <= N):
         
        # If answer[i] is -1, then minimum
        # can be substituted in that place
        if(answer[i] == -1):
            answer[i] = minimum
         
        # Find minimum answer
        else:
            answer[i] = min(minimum, answer[i])
        minimum = min(minimum, answer[i])
        i += 1
 
# Function to find the minimum number
# corresponding to every subarray of
# length K, for every K from 1 to N
def lengthOfSubarray(indices, st, N):
     
    # Stores the minimum common
    # elements for all subarray lengths
    #Initialize with -1.
    answer = [-1 for i in range(N + 1)]
     
    # Find for every element, the minimum length
    # such that the number is present in every
    # subsequence of that particular length or more
    for itr in st:
         
        # To store first occurence and
        # gaps between occurences
        start = -1
        gap = -1
         
        # To cover the distance between last
        # occurence and the end of the array
        indices[itr].append(N)
         
        # To find the distance
        # between any two occurences
        for i in range(len(indices[itr])):
            gap = max(gap, indices[itr][i] - start)
            start = indices[itr][i]
         
        if(answer[gap] == -1):
            answer[gap] = itr
     
    # Update and store the answer
    updateAnswerArray(answer, N)
     
    # Print the required answer
    printAnswer(answer, N)
     
# Function to find the smallest
# element common in all subarrays for
# every possible subarray lengths
def smallestPresentNumber(arr, N):
     
    # Initializing indices array
    indices = [[] for i in range(N + 1)]
     
    # Store the numbers present
    # in the array
    elements = []
     
    # Push the index in the indices[A[i]] and
    # also store the numbers in set to get
    # the numbers present in input array
    for i in range(N):
        indices[arr[i]].append(i)
        elements.append(arr[i])
     
    elements = list(set(elements))
     
    # Function call to calculate length of
    # subarray for which a number is present
    # in every subarray of that length
    lengthOfSubarray(indices, elements, N)
 
# Driver Code
 
# Given array
arr = [2, 3, 5, 3, 2, 3, 1, 3, 2, 7]
 
# Size of array
N = len(arr)
 
# Function Call
smallestPresentNumber(arr, N)
 
# This code is contributed by avanitrachhadiya2155
输出:
-1 -1 3 2 2 2 1 1 1 1

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