3 回答

TA貢獻1808條經驗 獲得超4個贊
根據更新,我認為您的問題可以簡化為:計算行或列中最小值或最大值的項目。如果沒問題,你的算法是錯誤的,因為:
您正在檢查列和行中的最小值(同時在兩者中)
你沒有檢查最大值
您正在打印找到的號碼
所以,你的策略應該是這樣的:
在零中創建一個計數器
對于矩陣中的每個項目
檢查他的行中是否是 min
檢查他的行中是否最大
檢查他的專欄中是否是 min
檢查他的列中是否最大
如果一張支票沒問題,增加計數器
打印或返回計數器
那應該對你有幫助。

TA貢獻1856條經驗 獲得超11個贊
我認為它可以以更好=更快的方式完成,但我的O(n^2):
import java.util.HashSet;
import java.util.Set;
public class Main {
public static int[][] input = {
{1, 3, 4},
{5, 2, 9},
{8, 7, 6}
};
public static void main(String[] args) {
int numberOfElements = 0;
Set<Integer> numberOfUniqueElements = new HashSet<>();
Set<Integer> specialElements = new HashSet<Integer>();
for (int i = 0; i < input.length; i++) {
int maxInRow = Integer.MIN_VALUE;
int minInRow = Integer.MAX_VALUE;
int maxInColumn = Integer.MIN_VALUE;
int minInColumn = Integer.MAX_VALUE;
for (int j = 0; j < input[i].length; j++) {
numberOfElements++;
numberOfUniqueElements.add(input[i][j]);
if (input[i][j] > maxInRow) {
maxInRow = input[i][j];
}
if (input[i][j] < minInRow) {
minInRow = input[i][j];
}
if (input[j][i] > maxInColumn) {
maxInColumn = input[j][i];
}
if (input[j][i] < minInColumn) {
minInColumn = input[j][i];
}
}
specialElements.add(minInRow);
specialElements.add(maxInRow);
specialElements.add(minInColumn);
specialElements.add(maxInColumn);
}
if (numberOfUniqueElements.size() != numberOfElements) {
System.out.println("-1");
} else {
System.out.println(specialElements.size());
}
}
}
添加回答
舉報