题目描述:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
题目分析:
暴力破解时间复杂度太高,本题有两种思路:
1. 将每行看成一个有序数组,用二分查找
2. 从左下角开始查找,若大于该值,右移;若小于该值,上移,直到找到为止
public class ArraySearch { public static boolean Find(int target, int [][] array) { int len1 = array.length; int len2 = array[0].length; for (int i = 0; i<len1 ; i++) for (int j=0; j<len2; j++){ if (target == array[i][j]) return true; } return false; } public static boolean Find1(int target, int[][] array){ int len1 = array.length; int len2 = array[0].length; int temp = 0; //从左下角开始查找 int row = len1 - 1 ; int col = 0 ; while (row >=0 && col <= len2-1){ temp = array[row][col]; if (target == temp) return true; if (target < temp) { row --; } if (target > temp) { col ++; } } return false; } public static boolean binarySearch(int target,int [] num){ int len = num.length; int left = 0; int right = len - 1; while (left <= right){ int mid = (right-left)/2 + left; if (target == num[mid]) return true; if (target > num[mid]){ left = mid+1; } if (target < num[mid]){ right = mid -1 ; } } return false; } public static boolean Find2(int target, int[][] array){ //二分查找 int len1 = array.length; int len2 = array[0].length; for (int i=0; i< len1; ++i ){ if (binarySearch(target,array[i])) return true; } return false; } public static void main(String[] args){ int[][] array = new int[4][3]; array[0][0] = 1;array[0][1] = 2;array[0][2] = 3; array[1][0] = 4;array[1][1] = 5;array[1][2] = 6; array[2][0] = 7;array[2][1] = 8;array[2][2] = 9; array[3][0] = 10;array[3][1] = 11;array[3][2] = 12; int target = 5; System.out.println(Find2(12,array)); } }