【发布时间】:2022-05-07 20:22:00
【问题描述】:
我正在为求职面试做评估。我必须在一小时内解决的 3 个问题之一是在网格中找到最大值,您可以在其中遍历它并根据给定的坐标将元素加 1。我在第二个问题上花了一点时间,最后只用了大约 20 分钟。我没有及时完成它,所以它困扰着我。
我只是想确保对我记忆中的问题的解决方案进行了优化。
输入是一个包含两个 int 值和网格维度的 String 数组。
为了说明,如果给定的坐标是 (3,2) (2,2) (1,3) 那么
[1][1][0]
[1][1][0]
[1][1][0]
[1][1][0]
[2][2][0]
[2][2][0]
[1][1][0]
[2][2][0]
[3][3][1]
等等……
我相信所需的结果是不在 (1,1) 中的最大值以及它在网格中存在的次数。
这是我想出的解决方案。有什么办法可以优化吗?
public static List<Integer> twoDimensions(String[] coordinates, int n) {
List<Integer> maxAndCount = new ArrayList<Integer>();
int[][] grid = new int[n][n];
int arrLength = coordinates.length;
int max = Integer.MIN_VALUE;
int count = 1;
for (int i = 0; i < arrLength; i++) {
String[] coors = coordinates[i].split(" ");
int row = Integer.parseInt(coors[0]);
int column = Integer.parseInt(coors[1]);
for (int j = 0; j < row; j++) {
for (int k = 0; k < column; k++) {
grid[j][k] += 1;
System.out.println("grid (" + j + "," + k + "): " + grid[j][k]);
if (!(j == 0 & k == 0) && grid[j][k] > max) {
max = grid[j][k];
count = 1;
} else if (grid[j][k] == max) {
count++;
}
}
}
}
maxAndCount.add(max);
maxAndCount.add(count);
return maxAndCount;
}
public static void main(String[] args) {
String[] coors = { "1 3", "2 4", "4 1", "3 2" };
System.out.println("The Max and count Are:" + twoDimensions(coors, 4).toString());
}
【问题讨论】:
-
我假设在你的图中,(1,1) 从左下角开始?我这样说是因为在编程中 (1,1) 通常从左上角开始。我看到你已经做了行主顺序(坐标中的第一个数字是指垂直距离)
-
另外我认为如果要添加的矩形总是从 (1,1) 开始,那么在删除 (1,1) 之后,最大值将总是在 (1,2) 或 (2,1) ,所以找到最大值只是比较这两个值,返回较大的值。也许还有其他你没有提到的条件?
标签: java optimization multidimensional-array