矩阵matrix的行和列都是非递减,给一个关键字key,判断是否在矩阵中。
思路:
1. matrix的行和列分别非递减,key与matrix右上角的元素比较。
case1: 相等,返回在矩阵;
case2: key < matrix右上角元素,去除最后一列;
case3: key > matrix 右上角元素,去除首行;
2. 不断循环。
算法:
点击(此处)折叠或打开
-
int qry_in_sorted_matrix(int *m, int rows, int cols, int key) {
-
int r = 0, c, result = 0;
-
if(m == NULL || rows <= 0 || cols <= 0) {
-
return 0;
-
}
-
-
c = cols - 1;
-
while(r < rows && c >= 0) {
-
if(key == m[r * cols + c]) {
-
result = 1;
-
break;
-
}
-
if(key > m[r * cols + c]) {
-
r++;
-
} else {
-
c--;
-
}
-
}
-
-
return result;
- }