讯飞2020正式批C++开发笔试题:一个n*m的矩阵,求其中不同行并且不同列的两个数的最大乘积。 n,m<1000
方法来自这里
我做了C++实现,随便测了几个例子,没有问题,没有做仔细测试,若有问题,欢迎留言!
#include<iostream>
#include<vector>
using namespace std;
int main(){
int n, m;
cin >> n >> m;
vector<vector<int>> myV(n, vector<int>(4, 0));
for (int i = 0; i < n; i++) {
int fir_max = 0, fir_max_j = 0, sec_max = 0, sec_max_j = 0;
for (int j = 0; j < m; j++) {
int temp;
cin >> temp;
if (temp > fir_max) { //更新最大的
sec_max = fir_max;
fir_max = temp;
sec_max_j = fir_max_j;
fir_max_j = j;
}
else if (temp > sec_max) { //更新次大的
sec_max = temp;
sec_max_j = j;
}
}
myV[i][0] = fir_max; // 存储最大值
myV[i][1] = fir_max_j;// 存储最大值列号
myV[i][2] = sec_max; // 存储次大值
myV[i][3] = sec_max_j;// 存储次大值列号
}
int ret_max = 0; // 最大值
for (int i = 0; i < n; i++) { //开始遍历 两两组合的行对
for (int j = 0; j < n; j++) {
if (i == j) continue; // 同一行不遍历
if (myV[i][1] != myV[j][1]) { //如果两行中最大值的列号不同,那么可以直接相乘
int tmp = myV[i][0] * myV[j][0];
ret_max = tmp > ret_max ? tmp : ret_max;
}
else {
// 如果两行中最大值的列号相同,最大值和次大值的列号必然不同,但是此时最大值和次大值均有两种取法(i,j)
// 应该取这两个乘积中的最大值
int tmp = max(myV[i][0] * myV[j][2], myV[i][2] * myV[j][1]);
ret_max = tmp > ret_max ? tmp : ret_max;
}
}
}
cout << ret_max << endl;
return 0;
}