码迷,mamicode.com
首页 > 编程语言 > 详细

面试10大算法题汇总-字符串和数组9

时间:2015-03-12 11:37:11      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:面试   算法   java   二分查找   

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));
	}
}


面试10大算法题汇总-字符串和数组9

标签:面试   算法   java   二分查找   

原文地址:http://blog.csdn.net/miaoyunzexiaobao/article/details/44218407

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!