search-a-2d-matrix

/**
*
* @author gentleKay
* Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
* Integers in each row are sorted from left to right.
* The first integer of each row is greater than the last integer of the previous row.
* For example,
* Consider the following matrix:
* [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
* Given target =3, returntrue.
*
* 写一个在m x n矩阵中搜索值的有效算法。此矩阵具有以下属性:
* 每行中的整数从左到右排序。
* 每行的第一个整数大于前一行的最后一个整数。
* 例如,
* 考虑以下矩阵:
* [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
* 给定目标=3,返回真。
*/

/**
 * 
 * @author gentleKay
 * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
 * Integers in each row are sorted from left to right.
 * The first integer of each row is greater than the last integer of the previous row.
 * For example,
 * Consider the following matrix:
 * 	[
  		[1,   3,  5,  7],
  		[10, 11, 16, 20],
  		[23, 30, 34, 50]
	]
 * Given target =3, returntrue.
 * 
 * 写一个在m x n矩阵中搜索值的有效算法。此矩阵具有以下属性:
 * 每行中的整数从左到右排序。
 * 每行的第一个整数大于前一行的最后一个整数。
 * 例如,
 * 考虑以下矩阵:
 * [
  		[1,   3,  5,  7],
  		[10, 11, 16, 20],
  		[23, 30, 34, 50]
   ]
 * 给定目标=3,返回真。
 */

public class Main24 {
	public static void main(String[] args) {
		int[][] matrix = {
				{1,3,5,7},
				{10,11,16,20},
				{23,30,34,50}
		};
		System.out.println(Main24.searchMatrix(matrix, 8));
	}
	
	public static boolean searchMatrix(int[][] matrix, int target) {
		if (matrix == null) {
			return false;
		}
		for (int i=0;i<matrix.length;i++) {
			for (int j=0;j<matrix[i].length;j++) {
				if (target == matrix[i][j]) {
					return true;
				}
			}
		}
        return false;
    }
}
原文地址:https://www.cnblogs.com/strive-19970713/p/11276653.html