算法 <矩阵中的幸运数> java暴力破解
要求如下
解题思路
二维数组是普通数组的数组
例:int[][] matrix = { {7, 8}, {1, 2}};
就是存储{7, 8}和{1, 2}这两个数组的数组
先把每个数组最小的数找出
再把最小的数拿去和其他数组中下标相同的值比较
代码
class Solution {
public List<Integer> luckyNumbers (int[][] matrix) {
int rowsLen = matrix.length; // 数组的个数
int colsLen = matrix[0].length; // 每个数组的长度
HashMap<Integer, Integer> minNumber = new HashMap<Integer, Integer>();
int minJudgment = 0; // 记录最小的数字
int minIndex = 0; // 记录最小数的索引
List<Integer> result = new ArrayList<Integer>();
// 先把每个数组最小的数找出
// 再把最小的数拿去和其他数组中下标相同的值比较
// 遍历出所有数组
for (int i = 0; i < rowsLen; i++) {
// 遍历出每个数组中,最小的数
minJudgment = matrix[i][0]; // 先保存数组中的第一个数
minIndex = 0; // 保存数组中的第一个数的下标,就是0
for (int j = 1; j < colsLen; j++) {
// 从第二个数开始,和前一位比较,保存较小的数
if (matrix[i][j] < minJudgment) {
minJudgment = matrix[i][j];
minIndex = j;
}
}
// 将该数和其他数组里相同下标的数字比较,只要小于其中一个数,就不添加这个数字
for (int j = 0; j < rowsLen; j++) {
// 判断是否小于其他数组的数字
if (minJudgment < matrix[j][minIndex]) {
minJudgment = -1; // 小于其他数组的数组,代表不是幸运数,用-1标记
break;
}
}
// 是-1标记的数,代表不是幸运数,就不添加该数
if (minJudgment != -1) {
result.add(minJudgment);
}
}
return result;
}
}
还没有评论,来说两句吧...