📌  相关文章
📜  数组中任意两个相等元素之间的最小距离

📅  最后修改于: 2021-09-06 11:07:48             🧑  作者: Mango

给定一个数组arr ,任务是找到数组中任意两个相同元素之间的最小距离。如果没有找到这样的元素,则返回 -1。
例子:

朴素的方法:最简单的方法是使用两个嵌套的 for 循环来形成每个组合。如果元素相等,求最小距离。
时间复杂度: O(N 2 )
有效方法:解决此问题的有效方法是使用 map 将数组元素存储为键,将它们的索引存储为值
下面是分步算法:

  1. 一一遍历数组。
  2. 检查此元素是否在地图中。
    • 如果地图不包含此元素,则将其插入为(element, current index) pair
    • 如果地图中存在数组元素,则从地图中获取该元素的前一个索引。
  3. 查找上一个索引和当前索引之间的差异
  4. 比较每个差异并找到最小距离。
  5. 如果没有找到这样的元素,则返回 -1。

下面是上述方法的实现。

C++
// C++ program to find the minimum distance
// between two occurrences of the same element
#include
using namespace std;
 
// Function to find the minimum
// distance between the same elements
int minimumDistance(int a[], int n)
{
 
    // Create a HashMap to
    // store (key, values) pair.
    map hmap;
 
    int minDistance = INT_MAX;
 
    // Initialize previousIndex
    // and currentIndex as 0
    int previousIndex = 0, currentIndex = 0;
 
    // Traverse the array and
    // find the minimum distance
    // between the same elements with map
 
    for (int i = 0; i < n; i++) {
 
        if (hmap.find(a[i])!=hmap.end()) {
            currentIndex = i;
 
            // Fetch the previous index from map.
            previousIndex = hmap[a[i]];
 
            // Find the minimum distance.
            minDistance = min((currentIndex -
                        previousIndex),minDistance);
        }
 
        // Update the map.
        hmap[a[i]] = i;
    }
 
    // return minimum distance,
    // if no such elements found, return -1
    return (minDistance == INT_MAX ? -1 : minDistance);
}
 
// Driver code
int main()
{
 
    // Test Case 1:
    int a1[] = { 1, 2, 3, 2, 1 };
    int n = sizeof(a1)/sizeof(a1[0]);
 
    cout << minimumDistance(a1, n) << endl;
 
    // Test Case 2:
    int a2[] = { 3, 5, 4, 6, 5, 3 };
    n = sizeof(a2)/sizeof(a2[0]);
    cout << minimumDistance(a2, n) << endl;
 
    // Test Case 3:
    int a3[] = { 1, 2, 1, 4, 1 };
    n = sizeof(a3)/sizeof(a3[0]);
 
    cout << minimumDistance(a3, n) << endl;
}
 
// This code is contributed by Sanjit_Prasad


Java
// Java program to find the minimum distance
// between two occurrences of the same element
 
import java.util.*;
import java.math.*;
 
class GFG {
 
    // Function to find the minimum
    // distance between the same elements
    static int minimumDistance(int[] a)
    {
 
        // Create a HashMap to
        // store (key, values) pair.
        HashMap hmap
            = new HashMap<>();
        int minDistance = Integer.MAX_VALUE;
 
        // Initialize previousIndex
        // and currentIndex as 0
        int previousIndex = 0, currentIndex = 0;
 
        // Traverse the array and
        // find the minimum distance
        // between the same elements with map
        for (int i = 0; i < a.length; i++) {
 
            if (hmap.containsKey(a[i])) {
                currentIndex = i;
 
                // Fetch the previous index from map.
                previousIndex = hmap.get(a[i]);
 
                // Find the minimum distance.
                minDistance
                    = Math.min(
                        (currentIndex - previousIndex),
                        minDistance);
            }
 
            // Update the map.
            hmap.put(a[i], i);
        }
 
        // return minimum distance,
        // if no such elements found, return -1
        return (
            minDistance == Integer.MAX_VALUE
                ? -1
                : minDistance);
    }
 
    // Driver code
    public static void main(String args[])
    {
 
        // Test Case 1:
        int a1[] = { 1, 2, 3, 2, 1 };
        System.out.println(minimumDistance(a1));
 
        // Test Case 2:
        int a2[] = { 3, 5, 4, 6, 5, 3 };
        System.out.println(minimumDistance(a2));
 
        // Test Case 3:
        int a3[] = { 1, 2, 1, 4, 1 };
        System.out.println(minimumDistance(a3));
    }
}


Python3
# Python3 program to find the minimum distance
# between two occurrences of the same element
 
# Function to find the minimum
# distance between the same elements
def minimumDistance(a):
 
    # Create a HashMap to
    # store (key, values) pair.
    hmap = dict()
    minDistance = 10**9
 
    # Initialize previousIndex
    # and currentIndex as 0
    previousIndex = 0
    currentIndex = 0
 
    # Traverse the array and
    # find the minimum distance
    # between the same elements with map
    for i in range(len(a)):
 
        if a[i] in hmap:
            currentIndex = i
 
            # Fetch the previous index from map.
            previousIndex = hmap[a[i]]
 
            # Find the minimum distance.
            minDistance = min((currentIndex -
                        previousIndex), minDistance)
 
        # Update the map.
        hmap[a[i]] = i
 
    # return minimum distance,
    # if no such elements found, return -1
    if minDistance == 10**9:
        return -1
    return minDistance
 
# Driver code
if __name__ == '__main__':
     
    # Test Case 1:
    a1 = [1, 2, 3, 2, 1 ]
    print(minimumDistance(a1))
 
    # Test Case 2:
    a2 = [3, 5, 4, 6, 5,3]
    print(minimumDistance(a2))
 
    # Test Case 3:
    a3 = [1, 2, 1, 4, 1 ]
    print(minimumDistance(a3))
     
# This code is contributed by mohit kumar 29


Javascript


输出:
2
3
2

时间复杂度: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live