📌  相关文章
📜  所有可能长度的子数组中的最小公共元素

📅  最后修改于: 2021-10-27 07:41:06             🧑  作者: Mango

给定一个数组arr[]由范围[1, N] 中N 个整数(允许重复)组成,任务是找到每个可能的子数组长度的最小公共元素。如果子数组的任何特定长度都不存在这样的元素,则打印-1

例子:

处理方法:按照以下步骤解决问题:

  • 遍历数组并将最后一次出现的每个元素存储在 Map 中。
  • 初始化一个数组temp[]并在其中存储每个值,即数组中任何一对连续重复之间的最大距离。
  • 完成上述步骤后,通过将temp[i]与最后一次出现的i与数组末尾的距离进行比较来更新temp[]
  • 现在,将所有长度为1N 的子数组的最小注释元素一一存储并打印出来。

下面是上述方法的实现:

C++
// C++ Program to implement the
// above approach
 
#include 
using namespace std;
 
// Function to find maximum distance
// between every two element
void max_distance(int a[], int temp[], int n)
{
    // Stores index of last occurence
    // of each array element
    map mp;
 
    // Initialize temp[] with -1
    for (int i = 1; i <= n; i++) {
        temp[i] = -1;
    }
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // If array element has
        // not occurred previously
        if (mp.find(a[i]) == mp.end())
 
            // Update index in temp
            temp[a[i]] = i + 1;
 
        // Otherwise
        else
 
            // Compare temp[a[i]] with distance
            // from its previous occurence and
            // store the maximum
            temp[a[i]] = max(temp[a[i]],
                             i - mp[a[i]]);
 
        mp[a[i]] = i;
    }
 
    for (int i = 1; i <= n; i++) {
 
        // Compare temp[i] with distance
        // of its last occurence from the end
        // of the array and store the maximum
        if (temp[i] != -1)
            temp[i] = max(temp[i], n - mp[i]);
    }
}
 
// Function to find the minimum common
// element in subarrays of all possible lengths
void min_comm_ele(int a[], int ans[],
                  int temp[], int n)
{
    // Function call to find a the maximum
    // distance between every pair of repetition
    max_distance(a, temp, n);
 
    // Initialize ans[] to -1
    for (int i = 1; i <= n; i++) {
        ans[i] = -1;
    }
 
    for (int i = 1; i <= n; i++) {
 
        // Check if subarray of length
        // temp[i] contains i as one
        // of the common elements
        if (ans[temp[i]] == -1)
            ans[temp[i]] = i;
    }
 
    for (int i = 1; i <= n; i++) {
 
        // Find the minimum of all
        // common elements
        if (i > 1 && ans[i - 1] != -1) {
 
            if (ans[i] == -1)
                ans[i] = ans[i - 1];
            else
                ans[i] = min(ans[i],
                             ans[i - 1]);
        }
 
        cout << ans[i] << " ";
    }
}
 
// Driver Code
int main()
{
    int N = 6;
    int a[] = { 1, 3, 4, 5, 6, 7 };
    int temp[100], ans[100];
    min_comm_ele(a, ans, temp, N);
 
    return 0;
}


Java
// Java program to implement the
// above approach
import java.util.*;
 
class GFG{
    
// Function to find maximum distance
// between every two element
static void max_distance(int a[], int temp[], int n)
{
     
    // Stores index of last occurence
    // of each array element
    Map mp = new HashMap();
 
    // Initialize temp[] with -1
    for(int i = 1; i <= n; i++)
    {
        temp[i] = -1;
    }
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
         
        // If array element has
        // not occurred previously
        if (mp.get(a[i]) == null)
         
            // Update index in temp
            temp[a[i]] = i + 1;
 
        // Otherwise
        else
 
            // Compare temp[a[i]] with distance
            // from its previous occurence and
            // store the maximum
            temp[a[i]] = Math.max(temp[a[i]],
                   i - mp.getOrDefault(a[i], 0));
 
        mp.put(a[i], i);
    }
 
    for(int i = 1; i <= n; i++)
    {
         
        // Compare temp[i] with distance
        // of its last occurence from the end
        // of the array and store the maximum
        if (temp[i] != -1)
            temp[i] = Math.max(temp[i],
                               n - mp.getOrDefault(i, 0));
    }
}
 
// Function to find the minimum common
// element in subarrays of all possible lengths
static void min_comm_ele(int a[], int ans[],
                         int temp[], int n)
{
     
    // Function call to find a the maximum
    // distance between every pair of repetition
    max_distance(a, temp, n);
 
    // Initialize ans[] to -1
    for(int i = 1; i <= n; i++)
    {
        ans[i] = -1;
    }
 
    for(int i = 1; i <= n; i++)
    {
         
        // Check if subarray of length
        // temp[i] contains i as one
        // of the common elements
        if (temp[i] >= 0 && ans[temp[i]] == -1)
            ans[temp[i]] = i;
    }
 
    for(int i = 1; i <= n; i++)
    {
         
        // Find the minimum of all
        // common elements
        if (i > 1 && ans[i - 1] != -1)
        {
            if (ans[i] == -1)
                ans[i] = ans[i - 1];
            else
                ans[i] = Math.min(ans[i],
                                  ans[i - 1]);
        }
        System.out.print(ans[i] + " ");
    }
}
 
// Driver Code
public static void main(String args[])
{
    int N = 6;
    int a[] = { 1, 3, 4, 5, 6, 7 };
     
    int []temp = new int[100];
    Arrays.fill(temp, 0);
     
    int []ans = new int[100];
    Arrays.fill(ans, 0);
     
    min_comm_ele(a, ans, temp, N);
}
}
 
// This code is contributed by SURENDRA_GANGWAR


Python3
# Python3 Program to implement
# the above approach
 
# Function to find maximum
# distance between every
# two element
def max_distance(a, temp, n):
 
    # Stores index of last
    # occurence of each
    # array element
    mp = {}
 
    # Initialize temp[]
    # with -1
    for i in range(1, n + 1):
        temp[i] = -1
 
    # Traverse the array
    for i in range(n):
 
        # If array element has
        # not occurred previously
        if (a[i] not in mp):
 
            # Update index in temp
            temp[a[i]] = i + 1
 
        # Otherwise
        else:
 
            # Compare temp[a[i]] with
            # distance from its previous
            # occurence and store the maximum
            temp[a[i]] = max(temp[a[i]],
                             i - mp[a[i]])
 
        mp[a[i]] = i
 
    for i in range(1, n + 1):
 
        # Compare temp[i] with
        # distance of its last
        # occurence from the end
        # of the array and store
        # the maximum
        if (temp[i] != -1):
            temp[i] = max(temp[i],
                          n - mp[i])
 
# Function to find the minimum
# common element in subarrays
# of all possible lengths
def min_comm_ele(a, ans,
                 temp, n):
 
    # Function call to find
    # a the maximum distance
    # between every pair of
    # repetition
    max_distance(a, temp, n)
 
    # Initialize ans[] to -1
    for i in range(1, n + 1):
        ans[i] = -1
 
    for i in range(1, n + 1):
 
        # Check if subarray of length
        # temp[i] contains i as one
        # of the common elements
        if (ans[temp[i]] == -1):
            ans[temp[i]] = i
 
    for i in range(1, n + 1):
 
        # Find the minimum of all
        # common elements
        if (i > 1 and
            ans[i - 1] != -1):
 
            if (ans[i] == -1):
                ans[i] = ans[i - 1]
            else:
                ans[i] = min(ans[i],
                             ans[i - 1])
 
        print(ans[i], end = " ")
 
# Driver Code
if __name__ == "__main__":
 
    N = 6
    a = [1, 3, 4, 5, 6, 7]
    temp = [0] * 100
    ans = [0] * 100
    min_comm_ele(a, ans,
                 temp, N)
 
# This code is contributed by Chitranayal


C#
// C# program to implement the
// above approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to find maximum distance
    // between every two element
    static void max_distance(int[] a, int[] temp, int n)
    {
          
        // Stores index of last occurence
        // of each array element
        Dictionary mp = new Dictionary(); 
      
        // Initialize temp[] with -1
        for(int i = 1; i <= n; i++)
        {
            temp[i] = -1;
        }
      
        // Traverse the array
        for(int i = 0; i < n; i++)
        {
              
            // If array element has
            // not occurred previously
            if (!mp.ContainsKey(a[i]))
              
                // Update index in temp
                temp[a[i]] = i + 1;
      
            // Otherwise
            else
      
                // Compare temp[a[i]] with distance
                // from its previous occurence and
                // store the maximum
                temp[a[i]] = Math.Max(temp[a[i]], i - mp[a[i]]);
             
            if(mp.ContainsKey(a[i]))
            {
                mp[a[i]] = i;
            }
            else{
                mp.Add(a[i], i);
            }
        }
      
        for(int i = 1; i <= n; i++)
        {
              
            // Compare temp[i] with distance
            // of its last occurence from the end
            // of the array and store the maximum
            if (temp[i] != -1)
            {
                if(mp.ContainsKey(i))
                {
                    temp[i] = Math.Max(temp[i], n - mp[i]);
                }
                else{
                    temp[i] = Math.Max(temp[i], n);
                }
            }
        }
    }
      
    // Function to find the minimum common
    // element in subarrays of all possible lengths
    static void min_comm_ele(int[] a, int[] ans,
                             int[] temp, int n)
    {
          
        // Function call to find a the maximum
        // distance between every pair of repetition
        max_distance(a, temp, n);
      
        // Initialize ans[] to -1
        for(int i = 1; i <= n; i++)
        {
            ans[i] = -1;
        }
      
        for(int i = 1; i <= n; i++)
        {
              
            // Check if subarray of length
            // temp[i] contains i as one
            // of the common elements
            if (temp[i] >= 0 && ans[temp[i]] == -1)
                ans[temp[i]] = i;
        }
      
        for(int i = 1; i <= n; i++)
        {
              
            // Find the minimum of all
            // common elements
            if (i > 1 && ans[i - 1] != -1)
            {
                if (ans[i] == -1)
                    ans[i] = ans[i - 1];
                else
                    ans[i] = Math.Min(ans[i],
                                      ans[i - 1]);
            }
            Console.Write(ans[i] + " ");
        }
    }
 
  // Driver code
  static void Main()
  {
       
        int N = 6;
        int[] a = { 1, 3, 4, 5, 6, 7 };
          
        int[] temp = new int[100];
        Array.Fill(temp, 0);
          
        int[] ans = new int[100];
        Array.Fill(ans, 0);
          
        min_comm_ele(a, ans, temp, N);
  }
}
 
// This code is contributed by divyeshrabadiya07


Javascript


输出:
-1 -1 -1 4 3 1

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程