📜  Array 中对数的差异等于数字反转的差异

📅  最后修改于: 2022-05-13 01:56:09.766000             🧑  作者: Mango

Array 中对数的差异等于数字反转的差异

给定一个由N个整数组成的数组arr[] ,任务是找到数组元素对(arr[i], arr[j])的数量,使得这些对之间的差等于两者的数字时的差数字是相反的。

例子:

方法:给定的问题可以通过使用基于以下观察的哈希来解决:

请按照以下步骤解决问题:

  • 现在,创建一个函数reverseDigits ,它将一个整数作为参数并反转该整数的数字。
  • 将值arr[i] – rev(arr[i])的频率存储在无序映射中,例如mp
  • 对于频率X的每个键(= 差) ,可以形成的对数由下式给出\binom{X}{2} = \frac{X * (X - 1)}{2}          .
  • 对的总数由存储在映射mp中的每个频率的上述表达式的值的总和给出。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to reverse the digits
// of an integer
int reverseDigits(int n)
{
    // Convert the given number
    // to a string
    string s = to_string(n);
 
    // Reverse the string
    reverse(s.begin(), s.end());
 
    // Return the value of the string
    return stoi(s);
}
int countValidPairs(vector arr)
{
    // Stores resultant count of pairs
    long long res = 0;
 
    // Stores the frequencies of
    // differences
    unordered_map mp;
    for (int i = 0; i < arr.size(); i++) {
        mp[arr[i] - reverseDigits(arr[i])]++;
    }
 
    // Traverse the map and count pairs
    // formed for all frequency values
    for (auto i : mp) {
        long long int t = i.second;
        res += t * (t - 1) / 2;
    }
 
    // Return the resultant count
    return res;
}
 
// Driver Code
int main()
{
    vector arr = { 1, 2, 3, 4 };
    cout << countValidPairs(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.HashMap;
 
class GFG {
 
    // Function to reverse the digits
    // of an integer
    public static int reverseDigits(int n)
    {
       
        // Convert the given number
        // to a string
        String s = String.valueOf(n);
 
        // Reverse the string
        s = new StringBuffer(s).reverse().toString();
 
        // Return the value of the string
        return Integer.parseInt(s);
    }
 
    public static int countValidPairs(int[] arr)
    {
       
        // Stores resultant count of pairs
        int res = 0;
 
        // Stores the frequencies of
        // differences
        HashMap mp = new HashMap();
        for (int i = 0; i < arr.length; i++) {
            if (mp.containsKey(arr[i] - reverseDigits(arr[i]))) {
                mp.put(arr[i] - reverseDigits(arr[i]), mp.get(arr[i] - reverseDigits(arr[i])) + 1);
            } else {
                mp.put(arr[i] - reverseDigits(arr[i]), 1);
            }
        }
 
        // Traverse the map and count pairs
        // formed for all frequency values
        for (int i : mp.keySet()) {
            int t = mp.get(i);
            res += t * (t - 1) / 2;
        }
 
        // Return the resultant count
        return res;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int[] arr = { 1, 2, 3, 4 };
        System.out.println(countValidPairs(arr));
    }
 
}
 
// This code is contributed by saurabh_jaiswal.


Python3
# python program for the above approach
 
# Function to reverse the digits
# of an integer
def reverseDigits(n):
 
    # Convert the given number
    # to a string
    s = str(n)
 
    # Reverse the string
    s = "".join(reversed(s))
 
    # Return the value of the string
    return int(s)
 
def countValidPairs(arr):
 
    # Stores resultant count of pairs
    res = 0
 
    # Stores the frequencies of
    # differences
    mp = {}
 
    for i in range(0, len(arr)):
        if not arr[i] - reverseDigits(arr[i]) in mp:
            mp[arr[i] - reverseDigits(arr[i])] = 1
        else:
            mp[arr[i] - reverseDigits(arr[i])] += 1
 
        # Traverse the map and count pairs
        # formed for all frequency values
    for i in mp:
        t = mp[i]
        res += (t * (t - 1)) // 2
 
        # Return the resultant count
    return res
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 2, 3, 4]
    print(countValidPairs(arr))
 
    # This code is contributed by rakeshsahni


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Function to reverse the digits
    // of an integer
    public static int reverseDigits(int n)
    {
 
        // Convert the given number
        // to a string
        string s = n.ToString();
 
        // Reverse the string
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        string st = new string(arr);
 
        // Return the value of the string
        return Int32.Parse(st);
    }
 
    public static int countValidPairs(int[] arr)
    {
 
        // Stores resultant count of pairs
        int res = 0;
 
        // Stores the frequencies of
        // differences
        Dictionary mp
            = new Dictionary();
        for (int i = 0; i < arr.Length; i++) {
            if (mp.ContainsKey(arr[i]
                               - reverseDigits(arr[i]))) {
                mp[arr[i] - reverseDigits(arr[i])]
                    = mp[arr[i] - reverseDigits(arr[i])]
                      + 1;
            }
            else {
                mp[arr[i] - reverseDigits(arr[i])] = 1;
            }
        }
 
        // Traverse the map and count pairs
        // formed for all frequency values
        foreach(int i in mp.Keys)
        {
            int t = mp[i];
            res += t * (t - 1) / 2;
        }
 
        // Return the resultant count
        return res;
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 4 };
        Console.WriteLine(countValidPairs(arr));
    }
}
 
// This code is contributed by ukasp.


Javascript


输出:
6

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