📌  相关文章
📜  数组中两次出现相同元素之间的最大距离

📅  最后修改于: 2021-10-27 09:02:57             🧑  作者: Mango

给定一个包含重复元素的数组,任务是找到一个元素两次出现之间的最大距离。

例子:

Input : arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}
Output: 10
// maximum distance for 2 is 11-1 = 10 
// maximum distance for 1 is 4-2 = 2 
// maximum distance for 4 is 10-5 = 5  

这个问题的一个简单解决方案是,一个一个地从数组中挑选每个元素,找到它在数组中的第一次最后一次出现,并取第一次和最后一次出现之间的差异以获得最大距离。这种方法的时间复杂度是 O(n 2 )。

这个问题的一个有效解决方案是使用散列。这个想法是遍历输入数组并将第一次出现的索引存储在哈希映射中。每隔一次,找出索引与哈希映射中存储的第一个索引之间的差异。如果到目前为止差异大于结果,则更新结果。

下面是这个想法的实现。实现中使用了 unordered_map。

C++
// C++ program to find maximum distance between two
// same occurrences of a number.
#include
using namespace std;
 
// Function to find maximum distance between equal elements
int maxDistance(int arr[], int n)
{
    // Used to store element to first index mapping
    unordered_map mp;
 
    // Traverse elements and find maximum distance between
    // same occurrences with the help of map.
    int max_dist = 0;
    for (int i=0; i


Java
// Java program to find maximum distance between two
// same occurrences of a number.
import java.io.*;
import java.util.*;
 
class GFG
{
 
    // Function to find maximum distance between equal elements
    static int maxDistance(int[] arr, int n)
    {
        // Used to store element to first index mapping
        HashMap map = new HashMap<>();
         
        // Traverse elements and find maximum distance between
        // same occurrences with the help of map.
        int max_dist = 0;
 
        for (int i = 0; i < n; i++)
        {
            // If this is first occurrence of element, insert its
            // index in map
            if (!map.containsKey(arr[i]))
                map.put(arr[i], i);
 
            // Else update max distance
            else
                max_dist = Math.max(max_dist, i - map.get(arr[i]));
        }
 
        return max_dist;
}
 
// Driver code
public static void main(String args[])
{
    int[] arr = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2};
    int n = arr.length;
    System.out.println(maxDistance(arr, n));
}
}
 
// This code is contributed by rachana soma


Python
# Python program to find maximum distance between two
# same occurrences of a number.
 
# Function to find maximum distance between equal elements
def maxDistance(arr, n):
     
    # Used to store element to first index mapping
    mp = {}
 
    # Traverse elements and find maximum distance between
    # same occurrences with the help of map.
    maxDict = 0
    for i in range(n):
 
        # If this is first occurrence of element, insert its
        # index in map
        if arr[i] not in mp.keys():
            mp[arr[i]] = i
 
        # Else update max distance
        else:
            maxDict = max(maxDict, i-mp[arr[i]])
 
    return maxDict
 
# Driver Program
if __name__=='__main__':
    arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2]
    n = len(arr)
    print maxDistance(arr, n)
         
# Contributed By: Harshit Sidhwa


C#
// C# program to find maximum distance between two
// same occurrences of a number.
 
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to find maximum distance between equal elements
    static int maxDistance(int[] arr, int n)
    {
        // Used to store element to first index mapping
        Dictionary map = new Dictionary();
         
        // Traverse elements and find maximum distance between
        // same occurrences with the help of map.
        int max_dist = 0;
 
        for (int i = 0; i < n; i++)
        {
            // If this is first occurrence of element, insert its
            // index in map
            if (!map.ContainsKey(arr[i]))
                map.Add(arr[i], i);
 
            // Else update max distance
            else
                max_dist = Math.Max(max_dist, i - map[arr[i]]);
        }
 
        return max_dist;
}
 
// Driver code
public static void Main(String []args)
{
    int[] arr = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2};
    int n = arr.Length;
    Console.WriteLine(maxDistance(arr, n));
}
}
 
// This code is contributed by PrinciRaj1992


Javascript


输出:

10

时间复杂度: O(n) 假设 unordered_map 的搜索和插入操作花费 O(1) 时间。

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