📜  与矩阵中的给定总和配对

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

给定一个 NxM 矩阵和一个总和 S。任务是检查矩阵中是否存在具有给定总和的对。
例子

Input: mat[N][M] = {{1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12},
                {13, 14, 15, 16}};
       sum = 31
Output: YES

Input: mat[N][M] = {{1, 2, 3, 4},
                {5, 6, 7, 8}};
       sum = 150
Output: NO

方法:

  • 取一个散列将矩阵的所有元素存储在散列中。
  • 开始遍历矩阵,并在遍历时检查哈希中是否存在 abs(sum-matrix_element)。
  • 如果存在,则返回 true,否则将当前矩阵元素插入到哈希中。
  • 如果遍历矩阵的所有元素并且没有找到对,则返回 false。

下面是上述方法的实现:

C++
// CPP code to check for pair with given sum
#include 
using namespace std;
 
#define N 4
#define M 4
 
// Function to check if a pair with given sum
// exists in the matrix
bool isPairWithSum(int mat[N][M], int sum)
{
    // hash to store elements
    unordered_set s;
 
    // looping through elements
    // if present in the matrix
    // return true, else push
    // the element in matrix
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (s.find(sum - mat[i][j]) != s.end()) {
                return true;
            }
            else {
                s.insert(mat[i][j]);
            }
        }
    }
 
    return false;
}
 
// Driver code
int main()
{
 
    // Input matrix
    int mat[N][M] = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 },
                      { 13, 14, 15, 16 } };
 
    // given sum
    int sum = 11;
 
    if (isPairWithSum(mat, sum)) {
        cout << "YES" << endl;
    }
    else
        cout << "NO" << endl;
 
    return 0;
}


Java
// Java code to check for pair
// with given sum
import java.util.*;
 
class GFG
{
     
// Function to check if a pair with
// given sum exists in the matrix
static final int N = 4;
static final int M = 4;
static boolean isPairWithSum(int [][]mat,
                             int sum)
{
    // hash to store elements
    Set s = new HashSet();
 
    // looping through elements
    // if present in the matrix
    // return true, else push
    // the element in matrix
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < M; j++)
        {
            if (s.contains(sum - mat[i][j]))
            {
                return true;
            }
            else
            {
                s.add(mat[i][j]);
            }
        }
    }
 
    return false;
}
 
// Driver code
public static void main(String []args)
{
 
    // Input matrix
    int [][]mat = { { 1, 2, 3, 4 },
                    { 5, 6, 7, 8 },
                    { 9, 10, 11, 12 },
                    { 13, 14, 15, 16 } };
 
    // given sum
    int sum = 11;
 
    if (isPairWithSum(mat, sum))
    {
        System.out.println("YES");
    }
    else
        System.out.println("NO");
}
}
 
// This code is contributed by ihritik


C#
// C# code to check for pair
// with given sum
using System;
using System.Collections.Generic;
 
class GFG
{
     
// Function to check if a pair with
// given sum exists in the matrix
static readonly int N = 4;
static readonly int M = 4;
static bool isPairWithSum(int [,]mat,
                            int sum)
{
    // hash to store elements
    HashSet s = new HashSet();
 
    // looping through elements
    // if present in the matrix
    // return true, else push
    // the element in matrix
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < M; j++)
        {
            if (s.Contains(sum - mat[i, j]))
            {
                return true;
            }
            else
            {
                s.Add(mat[i, j]);
            }
        }
    }
    return false;
}
 
// Driver code
public static void Main(String []args)
{
 
    // Input matrix
    int [,]mat = { { 1, 2, 3, 4 },
                    { 5, 6, 7, 8 },
                    { 9, 10, 11, 12 },
                    { 13, 14, 15, 16 } };
 
    // given sum
    int sum = 11;
 
    if (isPairWithSum(mat, sum))
    {
        Console.WriteLine("YES");
    }
    else
        Console.WriteLine("NO");
}
}
 
// This code contributed by Rajput-Ji


Python3
# python code to check for pair with given sum
 
N= 4
M= 4
 
# Function to check if a pair with given sum
# exists in the matrix
def isPairWithSum(mat, sum):
    # hash to store elements
    s = set()
 
    # looping through elements
    # if present in the matrix
    # return true, else push
    # the element in matrix
    for i in range(N):
        for j in range(M):
            if (sum - mat[i][j]) in s :
                return True
             
            else :
                s.add(mat[i][j])
             
    return False
 
 
# Driver code
if __name__ == '__main__':
 
    # Input matrix
    mat = [[ 1, 2, 3, 4 ],
                    [ 5, 6, 7, 8] ,
                    [ 9, 10, 11, 12] ,
                    [13, 14, 15, 16]] 
 
    # given sum
    sum = 11
 
    if (isPairWithSum(mat, sum)) :
        print("YES")
     
    else:
        print("NO")
 
     
# This code is contributed by AbhiThakur


PHP


Javascript


输出:

YES

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

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