一开始看过别人做的使用row和column来二分查找,
于是试着做了,结果错误了,花了三个小时修改,逻辑还是没找到,
自己最后用for循环做了,通过了
import java.util.*;
public class Finder {
public int[] findElement(int[][] mat, int n, int m, int x) {
// write code here
int[] index = new int[2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(x==mat[i][j]) {
index[0] = i;
index[1] = j;
}
}
}
return index;
}
}
看了人家的做法后自己改的:
import java.util.*;
public class Finder {
public int[] findElement(int[][] mat, int n, int m, int x) {
// write code here
int[] index = new int[2];
//右上角
int row = 0;
int column = m - 1;
//对于所有的行和列
while(row<n&&column>=0) {
//如果右上角的值大于x,那么那一列都大于x,剔除这一列,用column--
if(mat[row][column]>x)column--;
//如果右上角的值小于x,那么那一行都小于x,剔除这一行,用row++;
else if(mat[row][column]<x)row++;
else {
index[0] = row;
index[1] = column;
break;
}
//直到道找到
}
return index;
}
}
自己之前做的:
package sort;
import java.util.*;
import org.junit.Test;
public class Finder {
public int[] findElement(int[][] mat, int n, int m, int x) {
int row = 0;
int column = m - 1;
int[] index = get(x, mat, row, column, n, m);
return index;
}
//比较mat中的x和[row,column]的是否相等,并返回[row,column]
public int[] get(int x, int[][] mat, int row, int column, int n, int m) {
int[] index = new int[2];
if (x == mat[row][column]) {//x等于比较值
index[0] = row;
index[1] = column;
} else {
//x等于这列下一个值
//x大于这列下一个值,去下一行
//x大于这一行最大值,迭代循环get()
//x小于下列这个值,去上一行
if (x > mat[row][m - 1]) {
//比较列的大小
if(x==mat[row+1][column]) {
index[0] = row+1;
index[1] = column;
}
else if (x > mat[row+1][column]) {
//x大于等于本列下一个值,列往后挪
index = get(x, mat, row + 1, column + 1, n, m);
} else {
//x小于本列下一个值,列往前挪
index = get(x, mat, row + 1, column - 1, n, m);
}
}
//x
else {
//比较row行的每个值,直到找到值
for(int i = 0;i<=m-1;i++) {
//满足条件循环中断
if(x==mat[row][i]) {
index[0] = row;
index[1] = i;
break;
}
}
}
}
return index;
}
@Test
public void test() {
int[][] mat = { { 0, 164, 328, 492, 656, 820, 984, 1148, 1312, 1476 },
{ 4,168,332,496,660,824,988,1152,1316,1480 },
{ 8,172,336,500,664,828,992,1156,1320,1484 } };
int n = 3;
int m = 10;
int x = 1320;
int[] index = findElement(mat, n, m, x);
if (index == null)
System.out.println("null");
else {
System.out.println(index[0] + "," + index[1]);
}
}
}