📌  相关文章
📜  从具有相等和和商的数组中计算对

📅  最后修改于: 2021-10-27 07:54:36             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,任务是计算有效对(i, j) 的数量,使得arr[i] + arr[j] = arr[i] / arr[j]

例子:

朴素的方法:简单的方法是生成给定数组的所有可能对,并计算总和等于它们的除法的对的数量。检查后,所有对打印可能对的最终计数。

下面是上述方法的实现:

C++14
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count all pairs (i, j)
// such that a[i] + [j] = a[i] / a[j]
int countPairs(int a[], int n)
{
    // Stores total count of pairs
    int count = 0;
 
    // Generate all possible pairs
    for (int i = 0; i < n; i++) {
 
        for (int j = i + 1; j < n; j++) {
 
            if (a[j] != 0
                && a[i] % a[j] == 0) {
 
                // If a valid pair is found
                if ((a[i] + a[j])
                    == (a[i] / a[j]))
 
                    // Increment count
                    count++;
            }
        }
    }
 
    // Return the final count
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { -4, -3, 0, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << countPairs(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to count all pairs (i, j)
// such that a[i] + [j] = a[i] / a[j]
static int countPairs(int a[], int n)
{
    // Stores total count of pairs
    int count = 0;
 
    // Generate all possible pairs
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            if (a[j] != 0
                && a[i] % a[j] == 0) {
 
                // If a valid pair is found
                if ((a[i] + a[j])
                    == (a[i] / a[j]))
 
                    // Increment count
                    count++;
            }
        }
    }
 
    // Return the final count
    return count;
}
 
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { -4, -3, 0, 2, 1 };
    int N = arr.length;
    System.out.print(countPairs(arr, N));
}
}
 
// This code is contributed by code_hunt.


Python3
# Python3 program for the above approach
 
# Function to count all pairs (i, j)
# such that a[i] + [j] = a[i] / a[j]
def countPairs(a, n):
     
    # Stores total count of pairs
    count = 0
 
    # Generate all possible pairs
    for i in range(n):
        for j in range(i + 1, n):
            if (a[j] != 0 and a[i] % a[j] == 0):
 
                # If a valid pair is found
                if ((a[i] + a[j]) == (a[i] // a[j])):
 
                    # Increment count
                    count += 1
 
    # Return the final count
    return count
 
# Driver Code
if __name__ == '__main__':
    arr =[-4, -3, 0, 2, 1]
    N = len(arr)
    print (countPairs(arr, N))
 
    # This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
class GFG {
 
  // Function to count all pairs (i, j)
  // such that a[i] + [j] = a[i] / a[j]
  static int countPairs(int[] a, int n)
  {
 
    // Stores total count of pairs
    int count = 0;
 
    // Generate all possible pairs
    for (int i = 0; i < n; i++)
    {
      for (int j = i + 1; j < n; j++)
      {
        if (a[j] != 0
            && a[i] % a[j] == 0)
        {
 
          // If a valid pair is found
          if ((a[i] + a[j])
              == (a[i] / a[j]))
 
            // Increment count
            count++;
        }
      }
    }
 
    // Return the final count
    return count;
  }
 
  // Driver code
  static void Main() {
    int[] arr = { -4, -3, 0, 2, 1 };
    int N = arr.Length;
    Console.WriteLine(countPairs(arr, N));
  }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find number of pairs
// with equal sum and quotient
// from a given array
int countPairs(int a[], int n)
{
    // Store the count of pairs
    int count = 0;
 
    // Stores frequencies
    map mp;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        int y = a[i];
 
        // If y is neither 1 or 0
        if (y != 0 && y != 1) {
 
            // Evaluate x
            double x = ((y * 1.0)
                        / (1 - y))
                       * y;
 
            // Increment count by frequency
            // of x
            count += mp[x];
        }
 
        // Update map
        mp[y]++;
    }
 
    // Print the final count
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { -4, -3, 0, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countPairs(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to find number of pairs
// with equal sum and quotient
// from a given array
static int countPairs(int a[], int n)
{
   
    // Store the count of pairs
    int count = 0;
 
    // Stores frequencies
    HashMap mp = new HashMap();
 
    // Traverse the array
    for (int i = 0; i < n; i++)
    {
 
        double y = a[i];
 
        // If y is neither 1 or 0
        if (y != 0 && y != 1)
        {
 
            // Evaluate x
            double x = ((y * 1.0)
                        / (1 - y))
                       * y;
 
            // Increment count by frequency
            // of x
            if(mp.containsKey(x))
                count += mp.get(x);
        }
 
        // Update map
        if(mp.containsKey(y)){
            mp.put(y, mp.get(y)+1);
        }
        else{
            mp.put(y, 1);
        }
    }
 
    // Print the final count
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { -4, -3, 0, 2, 1 };
    int N = arr.length;
 
    // Function Call
    System.out.print(countPairs(arr, N));
 
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to find number of pairs
# with equal sum and quotient
# from a given array
def countPairs(a, n) :
     
    # Store the count of pairs
    count = 0
 
    # Stores frequencies
    mp = {}
 
    # Traverse the array
    for i in range(n):
 
        y = a[i]
 
        # If y is neither 1 or 0
        if (y != 0 and y != 1) :
 
            # Evaluate x
            x = (((y * 1.0)
                        // (1 - y))
                       * y)
 
            # Increment count by frequency
            # of x
            count += mp.get(x, 0)
         
        # Update map
        mp[y]  = mp.get(y, 0) + 1
     
    # Prthe final count
    return count
 
# Driver Code
 
arr = [ -4, -3, 0, 2, 1 ]
N = len(arr)
 
# Function Call
print(countPairs(arr, N))
 
# This code is contributed by susmitakundugoaldanga.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to find number of pairs
  // with equal sum and quotient
  // from a given array
  static int countPairs(int[] a, int n)
  {
 
    // Store the count of pairs
    int count = 0;
 
    // Stores frequencies
    Dictionary mp
      = new Dictionary();
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
      int y = a[i];
 
      // If y is neither 1 or 0
      if (y != 0 && y != 1) {
 
        // Evaluate x
        double x = ((y * 1.0) / (1 - y)) * y;
 
        // Increment count by frequency
        // of x
        if (!mp.ContainsKey(x))
          mp[x] = 0;
 
        count += mp[x];
      }
 
      // Update map
      if (!mp.ContainsKey(y))
        mp[y] = 0;
 
      mp[y]++;
    }
 
    // Print the final count
    return count;
  }
 
  // Driver Code
  public static void Main()
  {
    int[] arr = { -4, -3, 0, 2, 1 };
    int N = arr.Length;
 
    // Function Call
    Console.Write(countPairs(arr, N));
  }
}
 
// This code is contributed by ukasp.


Javascript


输出:
1

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

高效方法:可以通过简化给定表达式并使用 Map 计算满足以下简化条件的对数来优化上述方法:

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

  • 初始化一个变量,例如count ,以存储满足所需条件的所有可能对的计数。
  • 初始化一个 Map 来存储为每个数组元素获得的上述表达式的值的频率。
  • 使用变量i遍历给定数组并执行以下步骤:
    • 如果arr[i]不等于10 ,则计算arr[i] 2 /(1 – arr[i]) ,比如X
    • XMap 中的频率添加到count
    • Map中将arr[i]的频率增加1
  • 完成上述步骤后,打印计数的值作为结果。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to find number of pairs
// with equal sum and quotient
// from a given array
int countPairs(int a[], int n)
{
    // Store the count of pairs
    int count = 0;
 
    // Stores frequencies
    map mp;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        int y = a[i];
 
        // If y is neither 1 or 0
        if (y != 0 && y != 1) {
 
            // Evaluate x
            double x = ((y * 1.0)
                        / (1 - y))
                       * y;
 
            // Increment count by frequency
            // of x
            count += mp[x];
        }
 
        // Update map
        mp[y]++;
    }
 
    // Print the final count
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { -4, -3, 0, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countPairs(arr, N);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to find number of pairs
// with equal sum and quotient
// from a given array
static int countPairs(int a[], int n)
{
   
    // Store the count of pairs
    int count = 0;
 
    // Stores frequencies
    HashMap mp = new HashMap();
 
    // Traverse the array
    for (int i = 0; i < n; i++)
    {
 
        double y = a[i];
 
        // If y is neither 1 or 0
        if (y != 0 && y != 1)
        {
 
            // Evaluate x
            double x = ((y * 1.0)
                        / (1 - y))
                       * y;
 
            // Increment count by frequency
            // of x
            if(mp.containsKey(x))
                count += mp.get(x);
        }
 
        // Update map
        if(mp.containsKey(y)){
            mp.put(y, mp.get(y)+1);
        }
        else{
            mp.put(y, 1);
        }
    }
 
    // Print the final count
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { -4, -3, 0, 2, 1 };
    int N = arr.length;
 
    // Function Call
    System.out.print(countPairs(arr, N));
 
}
}
 
// This code is contributed by 29AjayKumar

蟒蛇3

# Python3 program for the above approach
 
# Function to find number of pairs
# with equal sum and quotient
# from a given array
def countPairs(a, n) :
     
    # Store the count of pairs
    count = 0
 
    # Stores frequencies
    mp = {}
 
    # Traverse the array
    for i in range(n):
 
        y = a[i]
 
        # If y is neither 1 or 0
        if (y != 0 and y != 1) :
 
            # Evaluate x
            x = (((y * 1.0)
                        // (1 - y))
                       * y)
 
            # Increment count by frequency
            # of x
            count += mp.get(x, 0)
         
        # Update map
        mp[y]  = mp.get(y, 0) + 1
     
    # Prthe final count
    return count
 
# Driver Code
 
arr = [ -4, -3, 0, 2, 1 ]
N = len(arr)
 
# Function Call
print(countPairs(arr, N))
 
# This code is contributed by susmitakundugoaldanga.

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to find number of pairs
  // with equal sum and quotient
  // from a given array
  static int countPairs(int[] a, int n)
  {
 
    // Store the count of pairs
    int count = 0;
 
    // Stores frequencies
    Dictionary mp
      = new Dictionary();
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
      int y = a[i];
 
      // If y is neither 1 or 0
      if (y != 0 && y != 1) {
 
        // Evaluate x
        double x = ((y * 1.0) / (1 - y)) * y;
 
        // Increment count by frequency
        // of x
        if (!mp.ContainsKey(x))
          mp[x] = 0;
 
        count += mp[x];
      }
 
      // Update map
      if (!mp.ContainsKey(y))
        mp[y] = 0;
 
      mp[y]++;
    }
 
    // Print the final count
    return count;
  }
 
  // Driver Code
  public static void Main()
  {
    int[] arr = { -4, -3, 0, 2, 1 };
    int N = arr.Length;
 
    // Function Call
    Console.Write(countPairs(arr, N));
  }
}
 
// This code is contributed by ukasp.

Javascript

          
输出:
1

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程