📅  最后修改于: 2023-12-03 15:08:06.153000             🧑  作者: Mango
题目描述:在一个按照螺旋排序的矩阵中查找一个元素是否存在,如果存在,返回其位置;若不存在,返回[-1,-1]。
螺旋排序矩阵如下:
1 2 3 4
10 11 12 5
9 8 7 6
该题可以使用二分查找的方式,通过折半将查找范围逐步缩小,最终找到目标元素的位置。
def searchMatrix(matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: List[int]
"""
if not matrix:
return [-1, -1]
rows, cols = len(matrix), len(matrix[0])
left, right = 0, rows * cols - 1
while left <= right:
mid = (left + right) // 2
num = matrix[mid // cols][mid % cols]
if num == target:
return [mid // cols, mid % cols]
elif num < target:
left = mid + 1
else:
right = mid - 1
return [-1, -1]
public int[] searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new int[]{-1, -1};
}
int rows = matrix.length;
int cols = matrix[0].length;
int left = 0;
int right = rows * cols - 1;
while (left <= right) {
int mid = (left + right) / 2;
int num = matrix[mid / cols][mid % cols];
if (num == target) {
return new int[]{mid / cols, mid % cols};
} else if (num < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return new int[]{-1, -1};
}