题解 | #二维数组中的查找#
二维数组中的查找
http://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e
package org.example.test;
public class TwoDimArrayFindTest {
public static void main(String[] args) {
int[][] test = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
System.out.println(find(10, test));
}
//从右边左,从上到下
public static boolean find(int target, int[][] array) {
int j = 0;
for (int[] ary : array) {
for (int value : ary) {
if (ary[j] > target) {
j--;
if (j < 0) {
j=0;
break;
}
} else if (ary[j] < target) {
j++;
if (j >= ary.length) {
j--;
break;
}
} else {
return true;
}
}
}
return false;
}
}