数组中两次出现相同元素的最大距离

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

例子:

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
// 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<Integer, Integer> 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

 

posted @ 2022-03-08 11:23  存钱罐  阅读(214)  评论(0编辑  收藏  举报