📌  相关文章
📜  数组中三元组的计数,使得 A[i] * A[j] = A[k] 并且 i < j < k

📅  最后修改于: 2021-10-27 08:43:51             🧑  作者: Mango

给定一个由N 个正整数组成的数组A[ ] ,任务是在数组中找到三元组A[i]、A[j] 和 A[k]的数量,使得i < j < kA[i] * A[j] = A[k]

例子:

天真的方法:
解决问题的最简单方法是生成所有可能的三元组,并针对每个三元组检查它是否满足所需条件。如果发现是真的,增加三胞胎的数量。在完整遍历数组并生成所有可能的三元组后,打印最终计数
时间复杂度: O(N 3 )
辅助空间: O(1)
有效的方法:
上述方法可以使用两个指针和 HashMap 进行优化。
请按照以下步骤解决问题:

  • 初始化 Map 以存储数组元素的频率。
  • 反向迭代数组,即使用范围[N – 2, 1] 中的变量j进行循环。
  • 对于每个j ,增加地图中A[j + 1]的计数。使用变量i在范围[0, j – 1] 上迭代并检查A[i] * A[j]是否存在于地图中
  • 如果A [1] * A [j]的在地图中发现,通过存储在地图A的频率[I] * A [j]的增加三胞胎的计数。
  • 完成数组遍历后,打印最终计数

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Returns total number of
// valid triplets possible
int countTriplets(int A[], int N)
{
    // Stores the count
    int ans = 0;
 
    // Map to store frequency
    // of array elements
    map map;
 
    for (int j = N - 2; j >= 1; j--) {
 
        // Increment the frequency
        // of A[j+1] as it can be
        // a valid A[k]
        map[A[j + 1]]++;
 
        for (int i = 0; i < j; i++) {
 
            int target = A[i] * A[j];
 
            // If target exists in the map
            if (map.find(target)
                != map.end())
                ans += map[target];
        }
    }
 
    // Return the final count
    return ans;
}
 
// Driver Code
int main()
{
    int N = 5;
    int A[] = { 2, 3, 4, 6, 12 };
 
    cout << countTriplets(A, N);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Returns total number of
// valid triplets possible
static int countTriplets(int A[], int N)
{
     
    // Stores the count
    int ans = 0;
 
    // Map to store frequency
    // of array elements
    HashMap map = new HashMap();
                                        
    for(int j = N - 2; j >= 1; j--)
    {
 
        // Increment the frequency
        // of A[j+1] as it can be
        // a valid A[k]
        if(map.containsKey(A[j + 1]))
            map.put(A[j + 1], map.get(A[j + 1]) + 1);
        else
            map.put(A[j + 1], 1);
 
        for(int i = 0; i < j; i++)
        {
            int target = A[i] * A[j];
 
            // If target exists in the map
            if (map.containsKey(target))
                ans += map.get(target);
        }
    }
 
    // Return the final count
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 5;
    int A[] = { 2, 3, 4, 6, 12 };
 
    System.out.print(countTriplets(A, N));
}
}
 
// This code is contributed by sapnasingh4991


Python3
# Python3 program for the above approach
from collections import defaultdict
 
# Returns total number of
# valid triplets possible
def countTriplets(A, N):
 
    # Stores the count
    ans = 0
 
    # Map to store frequency
    # of array elements
    map = defaultdict(lambda: 0)
 
    for j in range(N - 2, 0, -1):
 
        # Increment the frequency
        # of A[j+1] as it can be
        # a valid A[k]
        map[A[j + 1]] += 1
 
        for i in range(j):
            target = A[i] * A[j]
 
            # If target exists in the map
            if(target in map.keys()):
                ans += map[target]
 
    # Return the final count
    return ans
 
# Driver code
if __name__ == '__main__':
 
    N = 5
    A = [ 2, 3, 4, 6, 12 ]
 
    print(countTriplets(A, N))
 
# This code is contributed by Shivam Singh


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Returns total number of
// valid triplets possible
static int countTriplets(int []A, int N)
{
     
    // Stores the count
    int ans = 0;
 
    // Map to store frequency
    // of array elements
    Dictionary map = new Dictionary();
                                        
    for(int j = N - 2; j >= 1; j--)
    {
 
        // Increment the frequency
        // of A[j+1] as it can be
        // a valid A[k]
        if(map.ContainsKey(A[j + 1]))
            map[A[j + 1]] = map[A[j + 1]] + 1;
        else
            map.Add(A[j + 1], 1);
 
        for(int i = 0; i < j; i++)
        {
            int target = A[i] * A[j];
 
            // If target exists in the map
            if (map.ContainsKey(target))
                ans += map[target];
        }
    }
 
    // Return the readonly count
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 5;
    int []A = { 2, 3, 4, 6, 12 };
 
    Console.Write(countTriplets(A, N));
}
}
 
// This code is contributed by sapnasingh4991


Javascript


输出:
3

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

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