3种解法
/**
* NC86 矩阵元素查找
*/
public class NC86 {
public int[] findElement(int[][] mat, int n, int m, int x) {
// write code here
int[] ans = new int[2];
int i = n - 1;
int j = 0;
while (i >= 0 || j < m) {
if (mat[i][j] == x) {
ans[0] = i;
ans[1] = j;
return ans;
} else if (mat[i][j] < x) {
j++;
} else {
i--;
}
}
return ans;
}
public int[] findElement0(int[][] mat, int n, int m, int x) {
// write code here
int[] ans = new int[2];
for (int i = 0; i < n; i++) {
int l = 0;
int r = m - 1;
while (l <= r) {
int mi = l + ((r - l) >> 1);
if (mat[i][mi] == x) {
ans[0] = i;
ans[1] = mi;
return ans;
} else if (mat[i][mi] < x) {
l = mi + 1;
} else {
r = mi - 1;
}
}
}
return ans;
}
public int[] findElement1(int[][] mat, int n, int m, int x) {
// write code here
int[] ans = new int[2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == x) {
ans[0] = i;
ans[1] = j;
return ans;
}
}
}
return ans;
}
}