📌  相关文章
📜  计算数组中的对,使一个元素与另一个元素相反

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

给定一个数组arr[] ,任务是计算数组中的对,使元素彼此相反。

例子:

方法一:

方法:这个想法是使用嵌套循环来获取数组中所有可能的数字对。然后,对于每一对,检查一个元素是否与另一个元素相反。如果是,则将所需计数加一。检查完所有对后,它们返回或打印这些对的计数。

下面是上述方法的实现:

C++
// C++ program to count the pairs in array
// such that one element is reverse of another
#include 
using namespace std;
 
// Function to reverse the digits
// of the number
int reverse(int num)
{
    int rev_num = 0;
 
    // Loop to iterate till the number is
    // greater than 0
    while (num > 0) {
 
        // Extract the last digit and keep
        // multiplying it by 10 to get the
        // reverse of the number
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}
 
// Function to find the pairs from the array
// such that one number is reverse of
// the other
int countReverse(int arr[], int n)
{
    int res = 0;
 
    // Iterate through all pairs
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
 
            // Increment count if one is
            // the reverse of other
            if (reverse(arr[i]) == arr[j]) {
                res++;
            }
 
    return res;
}
 
// Driver code
int main()
{
    int a[] = { 16, 61, 12, 21, 25 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << countReverse(a, n);
    return 0;
}


Java
// Java program to count the pairs in array
// such that one element is reverse of another
 
class Geeks {
    // Function to reverse the digits
    // of the number
    static int reverse(int num) {
        int rev_num = 0;
 
        // Loop to iterate till the number is
        // greater than 0
        while (num > 0) {
 
            // Extract the last digit and keep
            // multiplying it by 10 to get the
            // reverse of the number
            rev_num = rev_num * 10 + num % 10;
            num = num / 10;
        }
        return rev_num;
    }
 
    // Function to find the pairs from the
    // such that one number is reverse of
    // the other
    static int countReverse(int arr[], int n) {
        int res = 0;
 
        // Iterate through all pairs
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
 
                // Increment count if one is
                // the reverse of other
                if (reverse(arr[i]) == arr[j]) {
                    res++;
                }
 
        return res;
    }
 
    // Driver code
    public static void main(String[] args) {
        int a[] = { 16, 61, 12, 21, 25 };
        int n = a.length;
        System.out.print(countReverse(a, n));
    }
}
 
// This code is contributed by Rajnis09


Python3
# Python3 program to count the pairs in array
# such that one element is reverse of another
 
# Function to reverse the digits
# of the number
def reverse(num):
    rev_num = 0
 
    # Loop to iterate till the number is
    # greater than 0
    while (num > 0):
 
        # Extract the last digit and keep
        # multiplying it by 10 to get the
        # reverse of the number
        rev_num = rev_num * 10 + num % 10
        num = num // 10
 
    return rev_num
 
# Function to find the pairs from the
# such that one number is reverse of
# the other
def countReverse(arr,n):
    res = 0
 
    # Iterate through all pairs
    for i in range(n):
        for j in range(i + 1, n):
 
            # Increment count if one is
            # the reverse of other
            if (reverse(arr[i]) == arr[j]):
                res += 1
 
    return res
 
# Driver code
if __name__ == '__main__':
    a =  [16, 61, 12, 21, 25]
    n =  len(a)
    print(countReverse(a, n))
 
# This code is contributed by Surendra_Gangwar


C#
// C# program to count the pairs in array
// such that one element is reverse of another
using System;
  
class GFG
{
  
// Function to reverse the digits
// of the number
static int reverse(int num)
{
    int rev_num = 0;
  
    // Loop to iterate till the number is
    // greater than 0
    while (num > 0) {
  
        // Extract the last digit and keep
        // multiplying it by 10 to get the
        // reverse of the number
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}
  
// Function to find the pairs from the
// such that one number is reverse of
// the other
static int countReverse(int []arr, int n)
{
    int res = 0;
  
    // Iterate through all pairs
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
  
            // Increment count if one is
            // the reverse of other
            if (reverse(arr[i]) == arr[j]) {
                res++;
            }
  
    return res;
}
  
// Driver code
public static void Main(String []arr)
{
    int []a = { 16, 61, 12, 21, 25 };
    int n = a.Length;
    Console.Write(countReverse(a, n));
}
}
 
// This code is contributed by shivanisinghss2110


Javascript


C++
// C++ program to count the pairs in array
// such that one element is reverse of another
#include 
using namespace std;
 
// Function to reverse the digits
// of the number
int reverse(int num)
{
    int rev_num = 0;
 
    // Loop to iterate till the number is
    // greater than 0
    while (num > 0) {
 
        // Extract the last digit and keep
        // multiplying it by 10 to get the
        // reverse of the number
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}
 
// Function to find the pairs from the array
// such that one number is reverse of
// the other
int countReverse(int arr[], int n)
{
    unordered_map freq;
 
    // Iterate over every element in the array
    // and increase the frequency of the element
    // in hash map
    for(int i = 0; i < n; ++i)
        ++freq[arr[i]];
 
    int res = 0;
    // Iterate over every element in the array
    for (int i = 0; i < n; i++){
 
        // remove the current element from
        // the hash map by decreasing the
        // frequency to avoid counting
        // when the number is a palindrome
        // or when we visit its reverse
        --freq[arr[i]];
 
        // Increment the count
        // by the frequency of
        // reverse of the number
        res += freq[reverse(arr[i])];
    }
    return res;
}
 
// Driver code
int main() {
    int a[] = { 16, 61, 12, 21, 25 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << countReverse(a, n) << '\n';
    return 0;
}


Java
// Java program to count the
// pairs in array such that
// one element is reverse of
// another
import java.util.*;
class GFG{
     
// Function to reverse the digits
// of the number
public static int reverse(int num)
{
  int rev_num = 0;
 
  // Loop to iterate till
  // the number is greater
  // than 0
  while (num > 0)
  {
    // Extract the last digit
    // and keep multiplying it
    // by 10 to get the reverse
    // of the number
    rev_num = rev_num * 10 +
              num % 10;
    num = num / 10;
  }
  return rev_num;
}
      
// Function to find the pairs
// from the array such that
// one number is reverse of the
// other
public static int countReverse(int arr[],
                               int n)
{
  HashMap freq =
          new HashMap<>();
 
  // Iterate over every element
  // in the array and increase
  // the frequency of the element
  // in hash map
  for(int i = 0; i < n; ++i)
  {
    if(freq.containsKey(arr[i]))
    {
      freq.replace(arr[i],
      freq.get(arr[i]) + 1);
    }
    else
    {
      freq.put(arr[i], 1);
    }
  }
 
  int res = 0;
   
  // Iterate over every element
  // in the array
  for (int i = 0; i < n; i++)
  {
    // remove the current element from
    // the hash map by decreasing the
    // frequency to avoid counting
    // when the number is a palindrome
    // or when we visit its reverse
    if(freq.containsKey(arr[i]))
    {
      freq.replace(arr[i],
      freq.get(arr[i]) - 1);
    }
    else
    {
      freq.put(arr[i], -1);
    }
 
    // Increment the count
    // by the frequency of
    // reverse of the number
    if(freq.containsKey(reverse(arr[i])))
    {
      res += freq.get(reverse(arr[i]));
    }
  }
  return res;
}
 
// Driver code   
public static void main(String[] args)
{
  int a[] = {16, 61, 12, 21, 25};
  int n = a.length;
  System.out.println(countReverse(a, n));
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program to count
# the pairs in array such
# that one element is reverse
# of another
from collections import defaultdict
 
# Function to reverse
# the digits of the number
def reverse(num):
 
    rev_num = 0
 
    # Loop to iterate till
    # the number is greater than 0
    while (num > 0):
 
        # Extract the last digit and keep
        # multiplying it by 10 to get the
        # reverse of the number
        rev_num = rev_num * 10 + num % 10
        num = num // 10
  
    return rev_num
 
# Function to find the pairs
# from the array such that
# one number is reverse of
# the other
def countReverse(arr, n):
 
    freq = defaultdict (int)
 
    # Iterate over every element
    # in the array and increase
    # the frequency of the element
    # in hash map
    for i in range (n):
        freq[arr[i]] += 1
 
    res = 0
     
    # Iterate over every
    # element in the array
    for i in range (n):
 
        # remove the current element from
        # the hash map by decreasing the
        # frequency to avoid counting
        # when the number is a palindrome
        # or when we visit its reverse
        freq[arr[i]] -= 1
 
        # Increment the count
        # by the frequency of
        # reverse of the number
        res += freq[reverse(arr[i])]
    
    return res
 
# Driver code
if __name__ == "__main__":
   
    a = [16, 61, 12, 21, 25]
    n = len(a)
    print (countReverse(a, n))
     
# This code is contributed by Chitranayal


C#
// C# program to count the
// pairs in array such that
// one element is reverse of
// another
using System;
using System.Collections.Generic;  
 
class GFG{
     
// Function to reverse the digits
// of the number
static int reverse(int num)
{
    int rev_num = 0;
     
    // Loop to iterate till
    // the number is greater
    // than 0
    while (num > 0)
    {
         
        // Extract the last digit
        // and keep multiplying it
        // by 10 to get the reverse
        // of the number
        rev_num = rev_num * 10 +
                      num % 10;
        num = num / 10;
    }
    return rev_num;
}
       
// Function to find the pairs
// from the array such that
// one number is reverse of the
// other
static int countReverse(int[] arr, int n)
{
    Dictionary freq = new Dictionary(); 
     
    // Iterate over every element
    // in the array and increase
    // the frequency of the element
    // in hash map
    for(int i = 0; i < n; ++i)
    {
        if (freq.ContainsKey(arr[i]))
        {
            freq[arr[i]]++;
        }
        else
        {
            freq.Add(arr[i], 1);
        }
    }
     
    int res = 0;
     
    // Iterate over every element
    // in the array
    for(int i = 0; i < n; i++)
    {
         
        // Remove the current element from
        // the hash map by decreasing the
        // frequency to avoid counting
        // when the number is a palindrome
        // or when we visit its reverse
        if (freq.ContainsKey(arr[i]))
        {
            freq[arr[i]]--;
        }
        else
        {
            freq.Add(arr[i], -1);
        }
     
        // Increment the count
        // by the frequency of
        // reverse of the number
        if (freq.ContainsKey(reverse(arr[i])))
        {
            res += freq[reverse(arr[i])];
        }
    }
    return res;
}
 
// Driver code   
static void Main()
{
    int[] a = { 16, 61, 12, 21, 25 };
    int n = a.Length;
     
    Console.WriteLine(countReverse(a, n));
}
}
 
// This code is contributed by divyesh072019


Javascript


输出:
2

时间复杂度:O(N 2 )

辅助空间:O(1)

方法二:(使用Hash-Map)

我们可以观察到,这里最昂贵的操作是搜索数组中的反转元素(需要 O(N))。通过使用哈希映射,这可以减少到 O(1)。

方法:想法是将数组的所有元素存储在哈希映射中(通过增加当前元素的频率来解决重复的问题)并检查反转元素重复的次数并增加该频率的计数.为了避免在回文数或我们访问其反向时重新计算数字,我们需要从哈希图中删除当前数字(这是通过降低该数字的频率来实现的)。

C++

// C++ program to count the pairs in array
// such that one element is reverse of another
#include 
using namespace std;
 
// Function to reverse the digits
// of the number
int reverse(int num)
{
    int rev_num = 0;
 
    // Loop to iterate till the number is
    // greater than 0
    while (num > 0) {
 
        // Extract the last digit and keep
        // multiplying it by 10 to get the
        // reverse of the number
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}
 
// Function to find the pairs from the array
// such that one number is reverse of
// the other
int countReverse(int arr[], int n)
{
    unordered_map freq;
 
    // Iterate over every element in the array
    // and increase the frequency of the element
    // in hash map
    for(int i = 0; i < n; ++i)
        ++freq[arr[i]];
 
    int res = 0;
    // Iterate over every element in the array
    for (int i = 0; i < n; i++){
 
        // remove the current element from
        // the hash map by decreasing the
        // frequency to avoid counting
        // when the number is a palindrome
        // or when we visit its reverse
        --freq[arr[i]];
 
        // Increment the count
        // by the frequency of
        // reverse of the number
        res += freq[reverse(arr[i])];
    }
    return res;
}
 
// Driver code
int main() {
    int a[] = { 16, 61, 12, 21, 25 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << countReverse(a, n) << '\n';
    return 0;
}

Java

// Java program to count the
// pairs in array such that
// one element is reverse of
// another
import java.util.*;
class GFG{
     
// Function to reverse the digits
// of the number
public static int reverse(int num)
{
  int rev_num = 0;
 
  // Loop to iterate till
  // the number is greater
  // than 0
  while (num > 0)
  {
    // Extract the last digit
    // and keep multiplying it
    // by 10 to get the reverse
    // of the number
    rev_num = rev_num * 10 +
              num % 10;
    num = num / 10;
  }
  return rev_num;
}
      
// Function to find the pairs
// from the array such that
// one number is reverse of the
// other
public static int countReverse(int arr[],
                               int n)
{
  HashMap freq =
          new HashMap<>();
 
  // Iterate over every element
  // in the array and increase
  // the frequency of the element
  // in hash map
  for(int i = 0; i < n; ++i)
  {
    if(freq.containsKey(arr[i]))
    {
      freq.replace(arr[i],
      freq.get(arr[i]) + 1);
    }
    else
    {
      freq.put(arr[i], 1);
    }
  }
 
  int res = 0;
   
  // Iterate over every element
  // in the array
  for (int i = 0; i < n; i++)
  {
    // remove the current element from
    // the hash map by decreasing the
    // frequency to avoid counting
    // when the number is a palindrome
    // or when we visit its reverse
    if(freq.containsKey(arr[i]))
    {
      freq.replace(arr[i],
      freq.get(arr[i]) - 1);
    }
    else
    {
      freq.put(arr[i], -1);
    }
 
    // Increment the count
    // by the frequency of
    // reverse of the number
    if(freq.containsKey(reverse(arr[i])))
    {
      res += freq.get(reverse(arr[i]));
    }
  }
  return res;
}
 
// Driver code   
public static void main(String[] args)
{
  int a[] = {16, 61, 12, 21, 25};
  int n = a.length;
  System.out.println(countReverse(a, n));
}
}
 
// This code is contributed by divyeshrabadiya07

蟒蛇3

# Python3 program to count
# the pairs in array such
# that one element is reverse
# of another
from collections import defaultdict
 
# Function to reverse
# the digits of the number
def reverse(num):
 
    rev_num = 0
 
    # Loop to iterate till
    # the number is greater than 0
    while (num > 0):
 
        # Extract the last digit and keep
        # multiplying it by 10 to get the
        # reverse of the number
        rev_num = rev_num * 10 + num % 10
        num = num // 10
  
    return rev_num
 
# Function to find the pairs
# from the array such that
# one number is reverse of
# the other
def countReverse(arr, n):
 
    freq = defaultdict (int)
 
    # Iterate over every element
    # in the array and increase
    # the frequency of the element
    # in hash map
    for i in range (n):
        freq[arr[i]] += 1
 
    res = 0
     
    # Iterate over every
    # element in the array
    for i in range (n):
 
        # remove the current element from
        # the hash map by decreasing the
        # frequency to avoid counting
        # when the number is a palindrome
        # or when we visit its reverse
        freq[arr[i]] -= 1
 
        # Increment the count
        # by the frequency of
        # reverse of the number
        res += freq[reverse(arr[i])]
    
    return res
 
# Driver code
if __name__ == "__main__":
   
    a = [16, 61, 12, 21, 25]
    n = len(a)
    print (countReverse(a, n))
     
# This code is contributed by Chitranayal

C#

// C# program to count the
// pairs in array such that
// one element is reverse of
// another
using System;
using System.Collections.Generic;  
 
class GFG{
     
// Function to reverse the digits
// of the number
static int reverse(int num)
{
    int rev_num = 0;
     
    // Loop to iterate till
    // the number is greater
    // than 0
    while (num > 0)
    {
         
        // Extract the last digit
        // and keep multiplying it
        // by 10 to get the reverse
        // of the number
        rev_num = rev_num * 10 +
                      num % 10;
        num = num / 10;
    }
    return rev_num;
}
       
// Function to find the pairs
// from the array such that
// one number is reverse of the
// other
static int countReverse(int[] arr, int n)
{
    Dictionary freq = new Dictionary(); 
     
    // Iterate over every element
    // in the array and increase
    // the frequency of the element
    // in hash map
    for(int i = 0; i < n; ++i)
    {
        if (freq.ContainsKey(arr[i]))
        {
            freq[arr[i]]++;
        }
        else
        {
            freq.Add(arr[i], 1);
        }
    }
     
    int res = 0;
     
    // Iterate over every element
    // in the array
    for(int i = 0; i < n; i++)
    {
         
        // Remove the current element from
        // the hash map by decreasing the
        // frequency to avoid counting
        // when the number is a palindrome
        // or when we visit its reverse
        if (freq.ContainsKey(arr[i]))
        {
            freq[arr[i]]--;
        }
        else
        {
            freq.Add(arr[i], -1);
        }
     
        // Increment the count
        // by the frequency of
        // reverse of the number
        if (freq.ContainsKey(reverse(arr[i])))
        {
            res += freq[reverse(arr[i])];
        }
    }
    return res;
}
 
// Driver code   
static void Main()
{
    int[] a = { 16, 61, 12, 21, 25 };
    int n = a.Length;
     
    Console.WriteLine(countReverse(a, n));
}
}
 
// This code is contributed by divyesh072019

Javascript


输出
2

时间复杂度:O(N)

辅助空间:O(N)