尝试编写一个返回MxN矩阵中心的方法,如果该中心不存在,则该方法应返回最接近具有最高整数值的中心的正方形的索引
例如1.-
[[5, 7, 8, 6, 3], [0, 0, 7, 0, 4], [4, 6, 3, 4, 9], [3, 1, 0, 5, 8]]
return [1,2](不存在中心,因此最靠近中心的是[[0,7,0],[6,3,4]],最大值为7)
例如2-
[[5, 7, 8, 6], [0, 0, 7, 0], [4, 6, 3, 4], [3, 1, 0, 5]]
返回[1,2](不存在中心,因此最接近中心的是[[0,7],[6,3]],最大值为7)
例如3.-
[[5, 7, 8], [0, 0, 7], [4, 6, 3]]
返回[1,1](中心存在)
private static int[] centerCoordinates(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
if (row % 2 != 0 && col % 2 != 0 && row == col)
return new int[]{row / 2, col / 2};
if (row % 2 == 0 && col % 2 == 0 && row == col) {
//calculate the max of internal square Eg 2.
return new int[]{x, y};
}
//where row!=col
}
我假设您在示例1中犯了一个错误,您给出了正确的答案,但是我认为所考虑的单元格应该仅是[[7],[3]]而不是3列宽。
基本上,如果尺寸是偶数,请检查长度/ 2-1和长度/ 2。
如果尺寸为奇数,则仅检查长度/ 2。
循环播放并获取最大
private static int[] centerCoordinates(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int[] ans = new int[]{row/2-(1-(row%2)), col/2-(1-(col%2))};
int best = Integer.MIN_VALUE;
for(int i=row/2-(1-(row%2));i<row/2+1;i++){
for(int j=col/2-(1-(col%2));j<col/2+1;j++){
if(matrix[i][j]>best){
best = matrix[i][j];
ans = new int[]{i,j};
}
}
}
return ans;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句