您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

使用C++编写,在矩阵中找到给定和的一对数字

2024/4/24 16:28:36发布3次查看
在本文中,我们将讨论在给定矩阵中查找具有给定和的对的程序。例如 -
input : matrix[n][m] = { { 4, 6, 4, 65 }, { 56, 1, 12, 32 }, { 4, 5, 6, 44 }, { 13, 9, 11, 25 } }, sum = 20output : pair exists.explanation : sum = 20 is equal to the sum of numbers 9 and 11 which exists in the matrix.input : matrix[n][m] = { { 5, 7, 3, 45 }, { 63, 5, 3, 7 }, { 11, 6, 9, 5 }, { 8, 6, 14, 15 } }, sum = 13output : pair does not exist.explanation : no pair exists in the matrix whose sum is equal to 7.
寻找解决方案的方法现在我们将解释两种不同的方法来寻找上述问题的解决方案。
暴力方法考虑给定矩阵中的每一对,检查该对的总和是否等于给定的 sum,如果是,则打印“pair isn't”;否则,打印“配对不存在”。应用这种方法非常简单,但它会将时间复杂度提高到 o((n*m)2)。
高效方法该程序可以通过使用hash存储所有矩阵元素,然后遍历矩阵并检查[ sum & (index element) ]的差值是否相等。如果是,则打印“exist”并退出程序。如果为no,则遍历print后,“不存在”。
示例#include <bits/stdc++.h>using namespace std;#define n 4#define m 4int main() { int matrix[n][m] = { { 5,7, 3,45 }, { 63, 5, 3, 7 }, { 11, 6, 9, 5 }, { 8, 6, 14, 15 } }; int sum = 7; unordered_set<int> hash; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (hash.find(sum - matrix[i][j]) != hash.end()) { cout << "pair exists." << endl; return 0; } else { hash.insert(matrix[i][j]); } } } cout << "pair does not exist." << endl; return 0;}
输出pair does not exist.
上述代码说明声明二维数组并在其中存储元素。遍历数组查找 if (sum - matrix[i][j]) != hash.end()。如果条件满足,则打印“pair contains”并从主函数返回。否则,继续遍历数组,最后打印“ pair does notise.”。结论在本文中,我们讨论了在矩阵中查找具有给定总和的对或二维数组;我们讨论了解决这个问题的暴力方法和有效方法。我们讨论了c++程序来解决这个问题。但是,我们可以用任何其他语言(例如 c、java、python 等)编写此程序。我们希望本文对您有所帮助。
以上就是使用c++编写,在矩阵中找到给定和的一对数字的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录