码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Search a 2D Matrix

时间:2014-07-29 15:14:31      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:java   io   for   ar   算法   leetcode   ef   public   

题目:给定一个有序的二维数组,判断数组中是否存在target

算法:逐行进行二分查找

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
	        for (int i=0; i<matrix.length; ++i) {
	        	if (horizontalBinarySearch(matrix, target, matrix[i].length, i)) {
	        		return true;
	        	}
	        }
	        return false;
	    }
	    
	    /**
	     * Binary Search horizontal
	     * @param matrix
	     * @param target
	     * @param length
	     * @param row
	     * @return
	     */
	    public boolean horizontalBinarySearch(int[][] matrix, int target, int length, int row) {
	    	int mid = 0;
	    	int left = 0;
	    	int right = length - 1;
	    	while (left <= right) {
	        	mid = (left + right) / 2;
	        	if (target == matrix[row][mid]) {
	        		return true;
	        	} else if (target < matrix[row][mid]) {
	        		right = mid - 1;
	        	} else {
	        		left = mid + 1;
	        	}
	        }
	        return false;
	    }
}

[LeetCode]Search a 2D Matrix,布布扣,bubuko.com

[LeetCode]Search a 2D Matrix

标签:java   io   for   ar   算法   leetcode   ef   public   

原文地址:http://blog.csdn.net/yeweiouyang/article/details/38267845

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