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

📅  最后修改于: 2021-04-22 09:10:06             🧑  作者: Mango

给定数组arr [] ,任务是对数组中的对进行计数,以使元素彼此相反。

例子:

方法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)
{
    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


输出:
2

时间复杂度:O(N 2 )

辅助空间:O(1)

方法2 :(使用哈希映射)

我们可以观察到,这里最昂贵的操作是在数组中搜索反向元素(需要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

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
输出
2

时间复杂度:O(N)

辅助空间:O(N)