20.寻找2D矩阵
给定一个从左到右从上到下递增的m*n矩阵,判断target是否在矩阵中
例:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Target=3
返回:true
思路:二分查找
Code:
public class test { public static boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; int m = matrix.length; int n = matrix[0].length; int begin = 0; int end = m * n - 1; while (begin < end) { int mid = (begin + end) / 2; int midX = mid / n; int midY = mid % n; if (matrix[midX][midY] == target) return true; if (matrix[midX][midY] < target) { begin = mid + 1; } else { end = mid - 1; } } return false; } public static void main(String[] args) { int[][] arr = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } }; System.out.println(searchMatrix(arr, 3)); } }
原文地址:http://blog.csdn.net/miaoyunzexiaobao/article/details/44218407