热门标签 | 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)


推荐阅读
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • C# 7.0 新特性:基于Tuple的“多”返回值方法
    本文介绍了C# 7.0中基于Tuple的“多”返回值方法的使用。通过对C# 6.0及更早版本的做法进行回顾,提出了问题:如何使一个方法可返回多个返回值。然后详细介绍了C# 7.0中使用Tuple的写法,并给出了示例代码。最后,总结了该新特性的优点。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • Python如何调用类里面的方法
    本文介绍了在Python中调用同一个类中的方法需要加上self参数,并且规范写法要求每个函数的第一个参数都为self。同时还介绍了如何调用另一个类中的方法。详细内容请阅读剩余部分。 ... [详细]
  • 本文介绍了RPC框架Thrift的安装环境变量配置与第一个实例,讲解了RPC的概念以及如何解决跨语言、c++客户端、web服务端、远程调用等需求。Thrift开发方便上手快,性能和稳定性也不错,适合初学者学习和使用。 ... [详细]
  • 本文探讨了C语言中指针的应用与价值,指针在C语言中具有灵活性和可变性,通过指针可以操作系统内存和控制外部I/O端口。文章介绍了指针变量和指针的指向变量的含义和用法,以及判断变量数据类型和指向变量或成员变量的类型的方法。还讨论了指针访问数组元素和下标法数组元素的等价关系,以及指针作为函数参数可以改变主调函数变量的值的特点。此外,文章还提到了指针在动态存储分配、链表创建和相关操作中的应用,以及类成员指针与外部变量的区分方法。通过本文的阐述,读者可以更好地理解和应用C语言中的指针。 ... [详细]
  • Python瓦片图下载、合并、绘图、标记的代码示例
    本文提供了Python瓦片图下载、合并、绘图、标记的代码示例,包括下载代码、多线程下载、图像处理等功能。通过参考geoserver,使用PIL、cv2、numpy、gdal、osr等库实现了瓦片图的下载、合并、绘图和标记功能。代码示例详细介绍了各个功能的实现方法,供读者参考使用。 ... [详细]
  • 闭包一直是Java社区中争论不断的话题,很多语言都支持闭包这个语言特性,闭包定义了一个依赖于外部环境的自由变量的函数,这个函数能够访问外部环境的变量。本文以JavaScript的一个闭包为例,介绍了闭包的定义和特性。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 从零学Java(10)之方法详解,喷打野你真的没我6!
    本文介绍了从零学Java系列中的第10篇文章,详解了Java中的方法。同时讨论了打野过程中喷打野的影响,以及金色打野刀对经济的增加和线上队友经济的影响。指出喷打野会导致线上经济的消减和影响队伍的团结。 ... [详细]
  • 本文讨论了如何使用IF函数从基于有限输入列表的有限输出列表中获取输出,并提出了是否有更快/更有效的执行代码的方法。作者希望了解是否有办法缩短代码,并从自我开发的角度来看是否有更好的方法。提供的代码可以按原样工作,但作者想知道是否有更好的方法来执行这样的任务。 ... [详细]
  • 本文介绍了使用cacti监控mssql 2005运行资源情况的操作步骤,包括安装必要的工具和驱动,测试mssql的连接,配置监控脚本等。通过php连接mssql来获取SQL 2005性能计算器的值,实现对mssql的监控。详细的操作步骤和代码请参考附件。 ... [详细]
  • IjustinheritedsomewebpageswhichusesMooTools.IneverusedMooTools.NowIneedtoaddsomef ... [详细]
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社区 版权所有