📌  相关文章
📜  数组中一组字谜的最大值和最小值之间的差异

📅  最后修改于: 2021-09-08 12:33:20             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,任务是找到数字互为异位词的整数,并打印它们的最大值和最小值之间的差值。如果没有任何数字形成字谜,则打印-1

注意:最多一组数组元素可以是彼此的字谜。该数组至少包含两个数字,并且给定数组中的所有数字长度相同。

例子:

方法:想法是通过为每个字谜编号生成唯一的哈希值,使用哈希来确定字谜。请按照以下步骤解决问题:

  • 使用素数进行散列,并通过用前 10 个素数初始化数组prime[10]将前 10 个素数分配给数字 0-9。
  • 然后,通过与arr[i] 的每个数字对应的素数相乘,找到每个数组元素arr[i]的哈希值。这样,对于不是字谜的数字,哈希值将不同。
  • 使用hashfunction(N)找到每个数组元素arr[i]的哈希值h
  • 将数组元素存储在 map 中,键作为它们的哈希值h
  • 遍历地图找到一个大小大于1的向量,并找到它的最大和最小元素。如果不存在这样的向量,则打印 -1。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Utility function to find the hash value
// for each element of the given array
int hashFunction(int N)
{
    // Initialize an array with
    // first 10 prime numbers
    int prime[10] = { 2, 3, 5, 7, 11,
                      13, 17, 19, 23, 29 };
 
    int value = 1, r;
 
    // Iterate over digits of N
    while (N != 0) {
        r = N % 10;
 
        // Update Hash Value
        value = value * prime[r];
 
        // Update N
        N = N / 10;
    }
    return value;
}
 
// Function to find the set of anagrams in the array
// and print the difference between the maximum and
// minimum of these numbers
void findDiff(int arr[], int n)
{
 
    // Map to store the hash value
    // and the array elements having that hash value
    map > m;
 
    int h, min, max;
    for (int i = 0; i < n; i++) {
 
        // Find the hash value for each arr[i]
        // by calling hash function
        h = hashFunction(arr[i]);
 
        m[h].push_back(arr[i]);
    }
 
    // Iterate over the map
    for (auto i = 0; i != m.size(); i++) {
 
        // If size of vector at m[i] greater than 1
        // then it must contain the anagrams
        if (m[i].size() > 1) {
 
            // Find the minimum and maximum
            // element of this anagrams vector
            min = *min_element(
                m[i].begin(), m[i].end());
            max = *max_element(
                m[i].begin(), m[i].end());
 
            // Display the difference
            cout << max - min;
            break;
        }
 
        // If the end of Map is reached,
        // then no anagrams are present
        else if (i == m.size() - 1)
            cout << -1;
    }
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 121, 312, 234,
                  211, 112, 102 };
 
    // Size of the array
    int N = sizeof(arr)
            / sizeof(arr[0]);
 
    findDiff(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Utility function to find the hash value
// for each element of the given array
static int hashFunction(int N)
{
     
    // Initialize an array with
    // first 10 prime numbers
    int[] prime = { 2, 3, 5, 7, 11, 13,
                    17, 19, 23, 29 };
     
    int value = 1, r;
     
    // Iterate over digits of N
    while (N != 0)
    {
        r = N % 10;
         
        // Update Hash Value
        value = value * prime[r];
         
        // Update N
        N = N / 10;
    }
    return value;
}
 
// Function to find the set of anagrams in the array
// and print the difference between the maximum and
// minimum of these numbers
static void findDiff(int[] arr, int n)
{
     
    // Map to store the hash value
    // and the array elements having that hash value
    HashMap> m = new HashMap<>();
     
    int h, min, max;
    for(int i = 0; i < n; i++)
    {
         
        // Find the hash value for each arr[i]
        // by calling hash function
        h = hashFunction(arr[i]);
         
        if (!m.containsKey(h))
        {
            m.put(h, new Vector());
        }
         
        m.get(h).add(arr[i]);
    }
     
    for(Map.Entry> i : m.entrySet())
    {
         
        // If size of vector at m[i] greater than 1
        // then it must contain the anagrams
        if (i.getValue().size() > 1)
        {
         
            // Find the minimum and maximum
            // element of this anagrams vector
            min = Integer.MAX_VALUE;
            max = -(Integer.MAX_VALUE);
             
            for (int j = 0; j < i.getValue().size(); j++)
            {
                if (m.get(i.getKey()).get(j) < min)
                {
                    min = m.get(i.getKey()).get(j);
                }
                 
                if (m.get(i.getKey()).get(j) > max)
                {
                    max = m.get(i.getKey()).get(j);
                }
            }
             
            // Display the difference
            System.out.print(max - min);
            break;
        }
         
        // If the end of Map is reached,
        // then no anagrams are present
        else if (m.get(i.getKey()) == m.values().toArray()[m.size() - 1])
            System.out.print(-1);
    }
}
 
// Driver code
public static void main(String[] args)
{
    // Given array
    int[] arr = { 121, 312, 234,
                 211, 112, 102 };
  
    // Size of the array
    int N = arr.length;
  
    findDiff(arr, N);
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program for the above approach
import math
from collections import defaultdict
 
# Utility function to find the hash value
# for each element of the given array
def hashFunction(N) :
     
    # Initialize an array with
    # first 10 prime numbers
    prime = [ 2, 3, 5, 7, 11,
                      13, 17, 19, 23, 29 ]
    value = 1
 
    # Iterate over digits of N
    while (N != 0) :
        r = N % 10
 
        # Update Hash Value
        value = value * prime[r]
 
        # Update N
        N = N // 10
    return value
 
# Function to find the set of anagrams in the array
# and print the difference between the maximum and
# minimum of these numbers
def findDiff(arr, n):
 
    # Map to store the hash value
    # and the array elements having that hash value
    m = defaultdict(lambda : [])
    for i in range(n):
 
        # Find the hash value for each arr[i]
        # by calling hash function
        h = hashFunction(arr[i])
        m[h].append(arr[i])
     
    # Iterate over the map
    i = 0
    while(i != len(m)) :
 
        # If size of vector at m[i] greater than 1
        # then it must contain the anagrams
        if (len(m[i]) > 1) :
 
            # Find the minimum and maximum
            # element of this anagrams vector
            minn = min(m[i])
            maxx = max(m[i])
 
            # Display the difference
            print(maxx - minn)
            break
         
        # If the end of Map is reached,
        # then no anagrams are present
        elif (i == (len(m) - 1)) :
            print(-1)   
        i += 1
     
# Driver Code
 
# Given array
arr = [ 121, 312, 234,
                211, 112, 102 ]
 
# Size of the array
N = len(arr)
findDiff(arr, N)
 
# This code is contributed by sanjoy_62.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
 
  // Utility function to find the hash value
  // for each element of the given array
  static int hashFunction(int N)
  {
    // Initialize an array with
    // first 10 prime numbers
    int[] prime = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
 
    int value = 1, r;
 
    // Iterate over digits of N
    while (N != 0) {
      r = N % 10;
 
      // Update Hash Value
      value = value * prime[r];
 
      // Update N
      N = N / 10;
    }
    return value;
  }
 
  // Function to find the set of anagrams in the array
  // and print the difference between the maximum and
  // minimum of these numbers
  static void findDiff(int[] arr, int n)
  {
 
    // Map to store the hash value
    // and the array elements having that hash value
    Dictionary> m = new Dictionary>();
 
    int h, min, max;
    for (int i = 0; i < n; i++) {
 
      // Find the hash value for each arr[i]
      // by calling hash function
      h = hashFunction(arr[i]);
 
      if(!m.ContainsKey(h))
      {
        m[h] = new List();
      }
 
      m[h].Add(arr[i]);
    }
 
    // Iterate over the map
    foreach(KeyValuePair> i in m)
    {
      // If size of vector at m[i] greater than 1
      // then it must contain the anagrams
      if (i.Value.Count > 1) {
 
        // Find the minimum and maximum
        // element of this anagrams vector
        min = Int32.MaxValue;
        max = Int32.MinValue;
        for(int j = 0; j < i.Value.Count; j++)
        {
          if(m[i.Key][j] < min)
          {
            min = m[i.Key][j];
          }
 
          if(m[i.Key][j] > max)
          {
            max = m[i.Key][j];
          }
        }
 
        // Display the difference
        Console.Write(max - min);
        break;
      }
 
      // If the end of Map is reached,
      // then no anagrams are present
      else if (m[i.Key].Equals( m.Last().Value ))
        Console.Write(-1);
    }
  }
 
  // Driver code
  static void Main()
  {
    // Given array
    int[] arr = { 121, 312, 234,
                 211, 112, 102 };
 
    // Size of the array
    int N = arr.Length;
 
    findDiff(arr, N);
  }
}
 
// This code is contributed by divyesh072019.


输出:
99

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

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