Skip to content

Instantly share code, notes, and snippets.

@Agenric
Last active June 7, 2017 14:11
Show Gist options
  • Save Agenric/59b1ca5b0fee341d7b9924e2932c1d03 to your computer and use it in GitHub Desktop.
Save Agenric/59b1ca5b0fee341d7b9924e2932c1d03 to your computer and use it in GitHub Desktop.
二维有序数组查找数字
public class Main {
public static void main(String[] args) {
int [][] array = {
{1,2,3,4},
{2,3,4,5},
{4,6,8,9},
{6,7,8,9},
{12,15,25,26}
};
System.out.print(findNumber(array, 5));
}
public static boolean findNumber(int[][] array, int number) {
if (array == null || array.length <= 0 || array[0].length <= 0) {
return false;
}
// 共有多少行,多少列
int rows = array.length;
int cols = array[0].length;
// 从当前矩阵的右上角开始查
int row = 0;
int col = cols - 1;
while (row >=0 && col >= 0 && row < rows && col < cols) {
if (array[row][col] > number) { // 当前右上角的值大于被查找数,说明该列所有的值都比被查数大,不必再查
col--;
} else if (array[row][col] < number) { // 当前右上角的值小于被查找数,说明该行所有的值都比被查数小,不必再查
row++;
} else if (array[row][col] == number) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment