您的位置:首页 > 编程语言 > Java开发

搜狗2016招聘笔试题<矩阵元素相乘>Java代码(

2017-08-16 18:24 211 查看
本文地址:http://blog.csdn.net/shanglianlm/article/details/77262611

题目:

A[n,m]是一个 n 行 m 列的矩阵,a[i,j] 表示 A 的第 i 行 j 列的元素,定义 x[i,j] 为 A 的第 i 行和第 j 列除了 a[i,j] 之外所有元素(共n+m-2个)的乘积,即x[i,j]=a[i,1]a[i,2]…a[i,j-1]…*a[i,m]*a[1,j]*a[2,j]…*a[i-1,j]*a[i+1,j]…*a[n,j],

现输入非负整形的矩阵 A[n,m],求 MAX(x[i,j]),即所有的 x[i,j] 中的最大值。

输入描述:

第一行两个整数n和m。之后n行输入矩阵,均为非负整数。

输出描述:

一行输出答案。

输入例子:

3 5

5 1 8 5 2

1 3 10 3 3

7 8 5 5 16

输出例子:

358400

代码

public class SougouMatrixMultiply {

public static int matrixMultiply(int[][] array,int rows,int cols){
int[][] mulArray = new int[rows][cols];

int[] rowTemp = new int[rows];
Arrays.fill(rowTemp, 1);
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
rowTemp[i] *= array[i][j];
}
}

int[] colTemp = new int[cols];
Arrays.fill(colTemp, 1);
for(int i=0;i<cols;i++){
for(int j=0;j<rows;j++){
colTemp[i] *= array[j][i];
}
}

for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
mulArray[i][j] = ((rowTemp[i]*colTemp[j])/array[i][j])/array[i][j];
}
}

System.out.println("乘积数组:");
int maxVal = 0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(mulArray[i][j]>maxVal){
maxVal = mulArray[i][j];
}
System.out.print(mulArray[i][j]+" ");
}
System.out.println();
}

return maxVal;
}

public static void main(String[] args) {
int rows = 3;
int cols = 5;
int[][] array = new int[rows][cols];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
array[i][j] = (int) Math.round(Math.random()*9+1);
}
}
System.out.println("输入数组:");
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}

int res = matrixMultiply(array,rows,cols);
System.out.println("最大值:"+res);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 招聘 搜狗