📜  与给定的产品配对 |设置 1(查找是否存在任何对)

📅  最后修改于: 2021-10-27 20:28:19             🧑  作者: Mango

给定一个由不同元素组成的数组和一个数字 x,查找是否存在乘积等于 x 的对。

例子 :

Input : arr[] = {10, 20, 9, 40};
        int x = 400;
Output : Yes

Input : arr[] = {10, 20, 9, 40};
        int x = 190;
Output : No

Input : arr[] = {-10, 20, 9, -40};
        int x = 400;
Output : Yes

Input : arr[] = {-10, 20, 9, 40};
        int x = -400;
Output : Yes

Input : arr[] = {0, 20, 9, 40};
        int x = 0;
Output : Yes

最简单的方法 ( O(n 2 ) )是运行两个循环来考虑所有可能的对。对于每一对,检查乘积是否等于 x。

C++
// A simple C++ program to find if there is a pair
// with given product.
#include
using namespace std;
 
// Returns true if there is a pair in arr[0..n-1]
// with product equal to x.
bool isProduct(int arr[], int n, int x)
{
    // Consider all possible pairs and check for
    // every pair.
    for (int i=0; i


Java
// Java program to find if there is a pair
// with given product.
class GFG
{   
    // Returns true if there is a pair in
    // arr[0..n-1] with product equal to x. 
    boolean isProduct(int arr[], int n, int x)
    {
        for (int i=0; i


Python3
# Python3 program to find if there
# is a pair with given product.
 
# Returns true if there is a
# pair in arr[0..n-1] with
# product equal to x
def isProduct(arr, n, x):
    for i in arr:
        for j in arr:
            if i * j == x:
                return True
    return False
     
     
# Driver code    
arr = [10, 20, 9, 40]
x = 400
n = len(arr)
if(isProduct(arr,n, x) == True):
    print ("Yes")
 
else:
    print("No")
     
x = 900
if(isProduct(arr, n, x)):
    print("Yes")
     
else:
    print("No")
 
# This code is contributed
# by prerna saini


C#
// C# program to find
// if there is a pair
// with given product.
using System;
 
class GFG
{
 
// Returns true if there
// is a pair in arr[0..n-1]
// with product equal to x.
static bool isProduct(int []arr,
                      int n, int x)
{
    for (int i = 0; i < n - 1; i++)
        for (int j = i + 1; j < n; j++)
            if (arr[i] * arr[j] == x)
                return true;
    return false;
}
 
// Driver Code
static void Main()
{
    int []arr = {10, 20, 9, 40};
    int x = 400;
    int n = arr.Length;
    if (isProduct(arr, n, x))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
 
    x = 190;
    if (isProduct(arr, n, x))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed
// by Sam007


PHP


Javascript


C++
// C++ program to find if there is a pair
// with given product.
#include
using namespace std;
 
// Returns true if there is a pair in arr[0..n-1]
// with product equal to x.
bool isProduct(int arr[], int n, int x)
{
    if (n < 2)
        return false;
 
    // Create an empty set and insert first
    // element into it
    unordered_set s;
 
    // Traverse remaining elements
    for (int i=0; i


Java
// Java program if there exists a pair for given product
import java.util.HashSet;
 
class GFG
{
    // Returns true if there is a pair in arr[0..n-1]
    // with product equal to x.
    static boolean isProduct(int arr[], int n, int x)
    {
        // Create an empty set and insert first
        // element into it
        HashSet hset = new HashSet<>();
         
        if(n < 2)
            return false;
         
        // Traverse remaining elements
        for(int i = 0; i < n; i++)
        {
            // 0 case must be handles explicitly as
            // x % 0 is undefined
            if(arr[i] == 0)
            {
                if(x == 0)
                    return true;
                else
                    continue;
            }
 
            // x/arr[i] exists in hash, then we
            // found a pair
            if(x % arr[i] == 0)
            {
                if(hset.contains(x / arr[i]))
                    return true;
 
            // Insert arr[i]
            hset.add(arr[i]);
            }
        }
        return false;
    }
     
    // driver code
    public static void main(String[] args)
    {
        int arr[] = {10, 20, 9, 40};
        int x = 400;
        int n = arr.length;
     
        if(isProduct(arr, arr.length, x))
        System.out.println("Yes");
        else
        System.out.println("No");
 
        x = 190;
     
        if(isProduct(arr, arr.length, x))
        System.out.println("Yes");
        else
        System.out.println("No");
    }
}
 
// This code is contributed by Kamal Rawal


Python3
# Python3 program to find if there
# is a pair with the given product.
 
# Returns true if there is a pair in
# arr[0..n-1] with product equal to x.
def isProduct(arr, n, x):
 
    if n < 2:
        return False
 
    # Create an empty set and insert
    # first element into it
    s = set()
 
    # Traverse remaining elements
    for i in range(0, n):
     
        # 0 case must be handles explicitly as
        # x % 0 is undefined behaviour in C++
        if arr[i] == 0:
         
            if x == 0:
                return True
            else:
                continue
 
        # x/arr[i] exists in hash, then
        # we found a pair
        if x % arr[i] == 0:
         
            if x // arr[i] in s:
                return True
 
            # Insert arr[i]
            s.add(arr[i])
     
    return False
 
# Driver code
if __name__ == "__main__":
 
    arr = [10, 20, 9, 40]
    x = 400
 
    n = len(arr)
    if isProduct(arr, n, x):
        print("Yes")
    else:
        print("No")
 
    x = 190
    if isProduct(arr, n, x):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# Rituraj Jain


C#
// C# program if there exists a
// pair for given product
using System;
using System.Collections.Generic;
 
class GFG
{
// Returns true if there is a pair
// in arr[0..n-1] with product equal to x.
public static bool isProduct(int[] arr,
                             int n, int x)
{
    // Create an empty set and insert
    // first element into it
    HashSet hset = new HashSet();
 
    if (n < 2)
    {
        return false;
    }
 
    // Traverse remaining elements
    for (int i = 0; i < n; i++)
    {
        // 0 case must be handles explicitly
        // as x % 0 is undefined
        if (arr[i] == 0)
        {
            if (x == 0)
            {
                return true;
            }
            else
            {
                continue;
            }
        }
 
        // x/arr[i] exists in hash, then
        // we found a pair
        if (x % arr[i] == 0)
        {
            if (hset.Contains(x / arr[i]))
            {
                return true;
            }
 
        // Insert arr[i]
        hset.Add(arr[i]);
        }
    }
    return false;
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] arr = new int[] {10, 20, 9, 40};
    int x = 400;
    int n = arr.Length;
 
    if (isProduct(arr, arr.Length, x))
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
 
    x = 190;
 
    if (isProduct(arr, arr.Length, x))
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
}
}
 
// This code is contributed by Shrikant13


Javascript


输出 :

Yes
No

更好的解决方案 (O(n Log n) :我们对给定的数组进行排序。排序后,我们遍历数组,对于每个元素 arr[i],我们在右边的子数组中对 x/arr[i] 进行二分搜索arr[i],即子数组 arr[i+1..n-1]

有效的解决方案( O(n) ):我们可以使用散列将时间复杂度提高到 O(n)。下面是步骤。

  1. 创建一个空的哈希表
  2. 遍历数组元素并对每个元素 arr[i] 执行以下操作。
    • 如果 arr[i] 为 0 且 x 也为 0,则返回 true,否则忽略 arr[i]。
    • 如果 x % arr[i] 为 0 并且表中存在 x/arr[i],则返回 true。
    • 将 arr[i] 插入哈希表。
  3. 返回假

下面是上述想法的实现。

C++

// C++ program to find if there is a pair
// with given product.
#include
using namespace std;
 
// Returns true if there is a pair in arr[0..n-1]
// with product equal to x.
bool isProduct(int arr[], int n, int x)
{
    if (n < 2)
        return false;
 
    // Create an empty set and insert first
    // element into it
    unordered_set s;
 
    // Traverse remaining elements
    for (int i=0; i

Java

// Java program if there exists a pair for given product
import java.util.HashSet;
 
class GFG
{
    // Returns true if there is a pair in arr[0..n-1]
    // with product equal to x.
    static boolean isProduct(int arr[], int n, int x)
    {
        // Create an empty set and insert first
        // element into it
        HashSet hset = new HashSet<>();
         
        if(n < 2)
            return false;
         
        // Traverse remaining elements
        for(int i = 0; i < n; i++)
        {
            // 0 case must be handles explicitly as
            // x % 0 is undefined
            if(arr[i] == 0)
            {
                if(x == 0)
                    return true;
                else
                    continue;
            }
 
            // x/arr[i] exists in hash, then we
            // found a pair
            if(x % arr[i] == 0)
            {
                if(hset.contains(x / arr[i]))
                    return true;
 
            // Insert arr[i]
            hset.add(arr[i]);
            }
        }
        return false;
    }
     
    // driver code
    public static void main(String[] args)
    {
        int arr[] = {10, 20, 9, 40};
        int x = 400;
        int n = arr.length;
     
        if(isProduct(arr, arr.length, x))
        System.out.println("Yes");
        else
        System.out.println("No");
 
        x = 190;
     
        if(isProduct(arr, arr.length, x))
        System.out.println("Yes");
        else
        System.out.println("No");
    }
}
 
// This code is contributed by Kamal Rawal

蟒蛇3

# Python3 program to find if there
# is a pair with the given product.
 
# Returns true if there is a pair in
# arr[0..n-1] with product equal to x.
def isProduct(arr, n, x):
 
    if n < 2:
        return False
 
    # Create an empty set and insert
    # first element into it
    s = set()
 
    # Traverse remaining elements
    for i in range(0, n):
     
        # 0 case must be handles explicitly as
        # x % 0 is undefined behaviour in C++
        if arr[i] == 0:
         
            if x == 0:
                return True
            else:
                continue
 
        # x/arr[i] exists in hash, then
        # we found a pair
        if x % arr[i] == 0:
         
            if x // arr[i] in s:
                return True
 
            # Insert arr[i]
            s.add(arr[i])
     
    return False
 
# Driver code
if __name__ == "__main__":
 
    arr = [10, 20, 9, 40]
    x = 400
 
    n = len(arr)
    if isProduct(arr, n, x):
        print("Yes")
    else:
        print("No")
 
    x = 190
    if isProduct(arr, n, x):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# Rituraj Jain

C#

// C# program if there exists a
// pair for given product
using System;
using System.Collections.Generic;
 
class GFG
{
// Returns true if there is a pair
// in arr[0..n-1] with product equal to x.
public static bool isProduct(int[] arr,
                             int n, int x)
{
    // Create an empty set and insert
    // first element into it
    HashSet hset = new HashSet();
 
    if (n < 2)
    {
        return false;
    }
 
    // Traverse remaining elements
    for (int i = 0; i < n; i++)
    {
        // 0 case must be handles explicitly
        // as x % 0 is undefined
        if (arr[i] == 0)
        {
            if (x == 0)
            {
                return true;
            }
            else
            {
                continue;
            }
        }
 
        // x/arr[i] exists in hash, then
        // we found a pair
        if (x % arr[i] == 0)
        {
            if (hset.Contains(x / arr[i]))
            {
                return true;
            }
 
        // Insert arr[i]
        hset.Add(arr[i]);
        }
    }
    return false;
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] arr = new int[] {10, 20, 9, 40};
    int x = 400;
    int n = arr.Length;
 
    if (isProduct(arr, arr.Length, x))
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
 
    x = 190;
 
    if (isProduct(arr, arr.Length, x))
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
}
}
 
// This code is contributed by Shrikant13

Javascript


输出 :

Yes
No

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