有序二维数组查找算法
假设给定一个有序二维数组,每一行都是从左到右递增,每一列都是从上到下递增,如何完成一个函数,输入这样一个二维数组和一个整数,判断这个整数是否在这个二维数组中。
假设一个4×4的有序二维数组:
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
错误的解法:
1 package findnum; 2 3 /** 4 * Created by Administrator on 2015/1/28. 5 */ 6 public class FindNumInMatrix { 7 /** 8 * @param matrix 9 * @param columnLen:列长度 10 * @param rowLen:行长度 11 * @return 12 */ 13 public static boolean searchMatrix(int[][] matrix, int columnLen, int rowLen, int target) { 14 int i = 0; 15 while (i < rowLen) { 16 if (target == matrix[i][columnLen - 1]) { 17 return true; 18 } else if (target > matrix[i][columnLen - 1]) { 19 i++; 20 } else { 21 break; 22 } 23 } 24 if (i == rowLen) { 25 return false; 26 } 27 //在找到的指定行中进行二分查找 28 int start = 0; 29 int end = columnLen - 1; 30 31 while (start <= end) { 32 int mid = (start + end) / 2; 33 if (target == matrix[i][mid]) { 34 return true; 35 } else if (target > matrix[i][mid]) { 36 start = mid + 1; 37 } else { 38 end = mid - 1; 39 40 } 41 } 42 43 44 return false; 45 } 46 47 48 public static void main(String[] args) { 49 int[][] matrix = { 50 {1, 3, 5, 7}, 51 {10, 11, 16, 20}, 52 {23, 30, 34, 50} 53 }; 54 System.out.println(FindNumInMatrix.searchMatrix(matrix, 4, 3, 100)); 55 56 57 } 58 59 }

浙公网安备 33010602011771号