热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

计算乘积等于K的所有不同对

计算乘积等于K的所有不同对原文:https://www.

计算乘积等于 K 的所有不同对

原文:https://www . geesforgeks . org/count-all-distinct-pairs-with-product-equal-to-k/

给定一个大小为 N 的整数数组arr【】和一个正整数 K ,任务是用等于 K 的乘积对数组中所有不同的对进行计数。
示例:

输入: arr[] = {1,5,3,4,2},K = 3
输出: 1
说明:
只有一对(1,3)积= K = 3。
输入: arr[] = {1,2,16,4,4},K = 16
输出: 2
说明:
有两对(1,16)和(4,4),乘积= K = 16。

高效方法: 想法是使用哈希。


  1. 最初,将数组中的所有元素插入到散列表中。插入时,如果 hashmap 中已经存在特定元素,则忽略。

  2. 现在,我们在散列中有所有唯一的元素。因此,对于数组 arr[i]中的每个元素,我们检查 hashmap 中是否存在 arr[i] / K

  3. 如果该值存在,那么我们增加计数并从散列中移除该特定元素(以获得唯一的对)。

以下是上述方法的实现:

C++


// C++ program to count the number of pairs
// whose product is equal to K
#include <algorithm>
#include <iostream>
using namespace std;
#define MAX 100000
// Function to count the number of pairs
// whose product is equal to K
int countPairsWithProductK(int arr[], int n, int k)
{
    // Initialize the count
    int count = 0;
    // Initialize empty hashmap.
    bool hashmap[MAX] = { false };
    // Insert array elements to hashmap
    for (int i = 0; i < n; i++)
        hashmap[arr[i]] = true;
    for (int i = 0; i < n; i++) {
        int x = arr[i];
        double index = 1.0 * k / arr[i];
        // Checking if the index is a whole number
        // and present in the hashmap
        if (index >= 0
            && ((index - (int)(index)) == 0)
            && hashmap[k / x])
            count++;
        hashmap[x] = false;
    }
    return count;
}
// Driver code
int main()
{
    int arr[] = { 1, 5, 3, 4, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
    cout << countPairsWithProductK(arr, N, K);
    return 0;
}


Java 语言(一种计算机语言,尤用于创建网站)


// Java program to count the number of pairs
// whose product is equal to K
class GFG
{
    static int MAX = 100000;
    // Function to count the number of pairs
    // whose product is equal to K
    static int countPairsWithProductK(int arr[], int n, int k)
    {
        // Initialize the count
        int count = 0;
        int i;
        // Initialize empty hashmap.
        boolean hashmap[] = new boolean[MAX];
        // Insert array elements to hashmap
        for (i = 0; i < n; i++)
            hashmap[arr[i]] = true;
        for (i = 0; i < n; i++) {
            int x = arr[i];
            double index = 1.0 * k / arr[i];
            // Checking if the index is a whole number
            // and present in the hashmap
            if (index >= 0
                && ((index - (int)(index)) == 0)
                && hashmap[k / x])
                count++;
            hashmap[x] = false;
        }
        return count;
    }
    // Driver code
    public static void main(String []args)
    {
        int arr[] = { 1, 5, 3, 4, 2 };
        int N = arr.length;
        int K = 3;
        System.out.print(countPairsWithProductK(arr, N, K));
    }
}


Python 3


# Python3 program to count the number of pairs
# whose product is equal to K
MAX = 100000;
# Function to count the number of pairs
# whose product is equal to K
def countPairsWithProductK(arr, n, k) :
    # Initialize the count
    count = 0;
    # Initialize empty hashmap.
    hashmap = [False]*MAX ;
    # Insert array elements to hashmap
    for i in range(n) :
        hashmap[arr[i]] = True;
    for i in range(n) :
        x = arr[i];
        index = 1.0 * k / arr[i];
        # Checking if the index is a whole number
        # and present in the hashmap
        if (index >= 0
            and ((index - int(index)) == 0)
            and hashmap[k // x]) :
                count += 1;
        hashmap[x] = False;
    return count;
# Driver code
if __name__ == "__main__" :
    arr = [ 1, 5, 3, 4, 2 ];
    N = len(arr);
    K = 3;
    print(countPairsWithProductK(arr, N, K));
# This code is contributed by AnkitRai01


C


// C# program to count the number of pairs
// whose product is equal to K     
using System;
class GFG
{
    static int MAX = 100000;
    // Function to count the number of pairs
    // whose product is equal to K
    static int countPairsWithProductK(int []arr, int n, int k)
    {
        // Initialize the count
        int count = 0;
        int i;
        // Initialize empty hashmap.
        bool []hashmap = new bool[MAX];
        // Insert array elements to hashmap
        for (i = 0; i < n; i++)
            hashmap[arr[i]] = true;
        for (i = 0; i < n; i++) {
            int x = arr[i];
            double index = 1.0 * k / arr[i];
            // Checking if the index is a whole number
            // and present in the hashmap
            if (index >= 0
                && ((index - (int)(index)) == 0)
                && hashmap[k / x])
                count++;
            hashmap[x] = false;
        }
        return count;
    }
    // Driver code
    public static void Main(String []args)
    {
        int []arr = { 1, 5, 3, 4, 2 };
        int N = arr.Length;
        int K = 3;
        Console.Write(countPairsWithProductK(arr, N, K));         
    }
}
// This code is contributed by 29AjayKumar


java 描述语言


<script>
// Javascript program to count the number of pairs
// whose product is equal to K
    let MAX = 100000;
    // Function to count the number of pairs
    // whose product is equal to K
    function countPairsWithProductK(arr,n,k)
    {
        // Initialize the count
        let count = 0;
        let i;
        // Initialize empty hashmap.
        let hashmap = new Array(MAX);
        // Insert array elements to hashmap
        for (i = 0; i < n; i++)
            hashmap[arr[i]] = true;
        for (i = 0; i < n; i++) {
            let x = arr[i];
            let index = 1.0 * k / arr[i];
            // Checking if the index is a whole number
            // and present in the hashmap
            if (index >= 0
                && ((index - Math.floor(index)) == 0)
                && hashmap[k / x])
                count++;
            hashmap[x] = false;
        }
        return count;
    }
    // Driver code
    let arr=[1, 5, 3, 4, 2];
    let N = arr.length;
    let K = 3;
    document.write(countPairsWithProductK(arr, N, K));
// This code is contributed by rag2127
script>

Output: 

1

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

辅助空间: O(MAX)


推荐阅读
  • 模板引擎StringTemplate的使用方法和特点
    本文介绍了模板引擎StringTemplate的使用方法和特点,包括强制Model和View的分离、Lazy-Evaluation、Recursive enable等。同时,还介绍了StringTemplate语法中的属性和普通字符的使用方法,并提供了向模板填充属性的示例代码。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • C# 7.0 新特性:基于Tuple的“多”返回值方法
    本文介绍了C# 7.0中基于Tuple的“多”返回值方法的使用。通过对C# 6.0及更早版本的做法进行回顾,提出了问题:如何使一个方法可返回多个返回值。然后详细介绍了C# 7.0中使用Tuple的写法,并给出了示例代码。最后,总结了该新特性的优点。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • Python如何调用类里面的方法
    本文介绍了在Python中调用同一个类中的方法需要加上self参数,并且规范写法要求每个函数的第一个参数都为self。同时还介绍了如何调用另一个类中的方法。详细内容请阅读剩余部分。 ... [详细]
  • 多维数组的使用
    本文介绍了多维数组的概念和使用方法,以及二维数组的特点和操作方式。同时还介绍了如何获取数组的长度。 ... [详细]
  • 本文介绍了Java中Hashtable的clear()方法,该方法用于清除和移除指定Hashtable中的所有键。通过示例程序演示了clear()方法的使用。 ... [详细]
  • 本文介绍了一个适用于PHP应用快速接入TRX和TRC20数字资产的开发包,该开发包支持使用自有Tron区块链节点的应用场景,也支持基于Tron官方公共API服务的轻量级部署场景。提供的功能包括生成地址、验证地址、查询余额、交易转账、查询最新区块和查询交易信息等。详细信息可参考tron-php的Github地址:https://github.com/Fenguoz/tron-php。 ... [详细]
  • 本文讨论了在VMWARE5.1的虚拟服务器Windows Server 2008R2上安装oracle 10g客户端时出现的问题,并提供了解决方法。错误日志显示了异常访问违例,通过分析日志中的问题帧,找到了解决问题的线索。文章详细介绍了解决方法,帮助读者顺利安装oracle 10g客户端。 ... [详细]
  • GreenDAO快速入门
    前言之前在自己做项目的时候,用到了GreenDAO数据库,其实对于数据库辅助工具库从OrmLite,到litePal再到GreenDAO,总是在不停的切换,但是没有真正去了解他们的 ... [详细]
author-avatar
Roger_丨8_8
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有