二维数组与一维数组转换
二维数组m行n列,一维数组索引为index
row = idx // n , col = idx % n。
标准二分查找算法
class Solution {
public boolean searchMatrix(int[][] matrix
, int target
) {
int m
= matrix
.length
;
if (m
== 0) return false;
int n
= matrix
[0].length
;
int left
= 0, right
= m
* n
- 1;
int pivotIdx
, pivotElement
;
while (left
<= right
) {
pivotIdx
= (left
+ right
) / 2;
pivotElement
= matrix
[pivotIdx
/ n
][pivotIdx
% n
];
if (target
== pivotElement
) return true;
else {
if (target
< pivotElement
) right
= pivotIdx
- 1;
else left
= pivotIdx
+ 1;
}
}
return false;
}
}
转载请注明原文地址: https://lol.8miu.com/read-9950.html