📌  相关文章
📜  给定数组的最大和最小元素之间的最小距离

📅  最后修改于: 2021-05-14 01:04:38             🧑  作者: Mango

给定一个由N个元素组成的数组A [] ,任务是找到该数组的最小和最大元素之间的最小距离。
例子:

天真的方法:
解决此问题的最简单方法如下:

  • 查找数组的最小和最大元素。
  • 遍历数组,对于每次出现的最大元素,从所有出现的最小元素开始计算其距离,并更新最小距离。
  • 遍历数组后,打印获得的所有最小距离。

时间复杂度: O(N 2 )
辅助空间: O(1)
高效方法:
请按照以下步骤优化上述方法:

  • 遍历数组以找到最小和最大元素。
  • 初始化两个变量min_indexmax_index分别存储数组的最小和最大元素的索引。用-1初始化它们。
  • 遍历数组。如果在任何时刻min_indexmax_index都不等于-1,即它们都已存储有效索引,请在此处计算差值。
  • 将此差异与最小距离(例如, min_dist )进行比较,并相应地更新min_dist
  • 最后,打印完成遍历数组后获得的min_dist的最终值。

下面是上述方法的实现:

C++
// C++ Program to implement the
// above approach
#include 
using namespace std;
 
// Function to find the minimum
// distance between the minimum
// and the maximum element
int minDistance(int a[], int n)
{
    // Stores the minimum and maximum
    // array element
    int maximum = -1, minimum = INT_MAX;
 
    // Stores the most recently traversed
    // indices of the minimum and the
    // maximum element
    int min_index = -1, max_index = -1;
 
    // Stores the minimum distance
    // between the minimum and the
    // maximium
    int min_dist = n + 1;
 
    // Find the maximum and
    // the minimum element
    // from the given array
    for (int i = 0; i < n; i++) {
 
        if (a[i] > maximum)
            maximum = a[i];
 
        if (a[i] < minimum)
            minimum = a[i];
    }
 
    // Find the minimum distance
    for (int i = 0; i < n; i++) {
 
        // Check if current element
        // is equal to minimum
        if (a[i] == minimum)
            min_index = i;
 
        // Check if current element
        // is equal to maximum
        if (a[i] == maximum)
            max_index = i;
 
        // If both the minimum and the
        // maximum element has
        // occurred at least once
        if (min_index != -1
            && max_index != -1)
 
            // Update the minimum distance
            min_dist
                = min(min_dist,
                      abs(min_index
                          - max_index));
    }
 
    // Return the answer
    return min_dist;
}
 
// Driver Code
int main()
{
    int a[] = { 3, 2, 1, 2, 1, 4,
                5, 8, 6, 7, 8, 2 };
    int n = sizeof a / sizeof a[0];
    cout << minDistance(a, n);
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG {
 
    // Function to find the minimum
    // distance between the minimum
    // and the maximum element
    public static int minDistance(int a[], int n)
    {
 
        // Stores the minimum and maximum
        // array element
        int max = -1, min = Integer.MAX_VALUE;
 
        // Stores the most recently traversed
        // indices of the minimum and the
        // maximum element
        int min_index = -1, max_index = -1;
 
        // Stores the minimum distance
        // between the minimum and the
        // maximium
        int min_dist = n + 1;
 
        // Find the maximum and
        // the minimum element
        // from the given array
        for (int i = 0; i < n; i++) {
            if (a[i] > max)
                max = a[i];
            if (a[i] < min)
                min = a[i];
        }
 
        // Find the minimum distance
        for (int i = 0; i < n; i++) {
 
            // Check if current element
            // is equal to minimum
            if (a[i] == min)
                min_index = i;
 
            // Check if current element
            // is equal to maximum
            if (a[i] == max)
                max_index = i;
 
            // If both the minimum and the
            // maximum element has
            // occurred at least once
            if (min_index != -1
                && max_index != -1)
                min_dist
                    = Math.min(min_dist,
                               Math.abs(min_index
                                        - max_index));
        }
        return min_dist;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int n = 12;
        int a[] = { 3, 2, 1, 2, 1, 4,
                    5, 8, 6, 7, 8, 2 };
        System.out.println(minDistance(a, n));
    }
}


Python3
# Python3 Program to implement the
# above approach
import sys
 
# Function to find the minimum
# distance between the minimum
# and the maximum element
def minDistance(a, n):
 
    # Stores the minimum and maximum
    # array element
    maximum = -1
    minimum = sys.maxsize
  
    # Stores the most recently traversed
    # indices of the minimum and the
    # maximum element
    min_index = -1
    max_index = -1
  
    # Stores the minimum distance
    # between the minimum and the
    # maximium
    min_dist = n + 1
  
    # Find the maximum and
    # the minimum element
    # from the given array
    for i in range (n):
        if (a[i] > maximum):
            maximum = a[i]
 
        if (a[i] < minimum):
            minimum = a[i]
  
    # Find the minimum distance
    for i in range (n):
  
        # Check if current element
        # is equal to minimum
        if (a[i] == minimum):
            min_index = i
  
        # Check if current element
        # is equal to maximum
        if (a[i] == maximum):
            max_index = i
  
        # If both the minimum and the
        # maximum element has
        # occurred at least once
        if (min_index != -1 and
            max_index != -1):
  
            # Update the minimum distance
            min_dist = (min(min_dist,
                        abs(min_index -
                            max_index)))
  
    # Return the answer
    return min_dist
  
# Driver Code
if __name__ == "__main__":
 
    a = [3, 2, 1, 2, 1, 4,
         5, 8, 6, 7, 8, 2]
    n = len(a)
    print (minDistance(a, n))
 
# This code is contributed by Chitranayal


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
     
// Function to find the minimum
// distance between the minimum
// and the maximum element
static int minDistance(int []a, int n)
{
     
    // Stores the minimum and maximum
    // array element
    int max = -1, min = Int32.MaxValue;
 
    // Stores the most recently traversed
    // indices of the minimum and the
    // maximum element
    int min_index = -1, max_index = -1;
 
    // Stores the minimum distance
    // between the minimum and the
    // maximium
    int min_dist = n + 1;
 
    // Find the maximum and
    // the minimum element
    // from the given array
    for(int i = 0; i < n; i++)
    {
        if (a[i] > max)
            max = a[i];
        if (a[i] < min)
            min = a[i];
    }
 
    // Find the minimum distance
    for(int i = 0; i < n; i++)
    {
        // Check if current element
        // is equal to minimum
        if (a[i] == min)
            min_index = i;
 
        // Check if current element
        // is equal to maximum
        if (a[i] == max)
            max_index = i;
 
        // If both the minimum and the
        // maximum element has
        // occurred at least once
        if (min_index != -1 && max_index != -1)
            min_dist = Math.Min(min_dist,
                                Math.Abs(
                                min_index -
                                max_index));
    }
    return min_dist;
}
 
// Driver Code
public static void Main()
{
    int n = 12;
    int []a = { 3, 2, 1, 2, 1, 4,
                5, 8, 6, 7, 8, 2 };
                 
    Console.WriteLine(minDistance(a, n));
}
}
 
// This code is contributed by piyush3010


输出:
3

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