首页 > 其他 > 详细

Jan 20 - Search a 2D array; 2D Array; Binary Search;

时间:2016-01-21 06:56:13      阅读:225      评论:0      收藏:0      [点我收藏+]

First, we use binary search in the last column to find which row the target supposed to be in. Initially, we set rowLow = 0, rowHigh = row-1. The condition of the while loop is rowLow < rowHigh. we get the middle postion of rowLow and rowHigh, which is rowMid = (rowLow+rowHigh)/2, here we do not need to concern about the overrange of integer value. we compare the value in the middle position, if equal to target, return true; if larger than target, set high = mid-1; if smaller than target, set low = mid+1; Finally when the loop ends, the rowLow equals to rowHigh, and we only leave the row-rowLow unchecked. Then we compare the value of matrix[rowLow][col-1] with target, if same return true, if smaller than target, then the target should be in the row ++rowLow, but if rowLow == row, that means target is larger than biggest value in the matrix, return false. Then we examine the row rowLow. Once again we use binary search to find whether target is in the row.

Code:

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int row = matrix.length;
        int col = matrix[0].length;
        if(row == 0 || col == 0) return false;
        int rowLow = 0, rowHigh = row-1;
        int colLow = 0, colHigh = col-1;
        while(rowLow < rowHigh){
            int rowMid = (rowLow + rowHigh)/2;
            if(target == matrix[rowMid][col-1]) return true;
            else if(target < matrix[rowMid][col-1]) rowHigh = rowMid - 1;
            else rowLow = rowMid + 1;
        }
        if(matrix[rowLow][col-1] == target) return true;
        if(matrix[rowLow][col-1] < target) rowLow++;
        if(rowLow == row) return false;
        while(colLow < colHigh){
            int colMid = (colLow+colHigh)/2;
            if(target == matrix[rowLow][colMid]) return true;
            else if(target < matrix[rowLow][colMid]) colHigh = colMid - 1;
            else colLow = colMid + 1;
        }
        if(matrix[rowLow][colLow] == target) return true;
        else return false;
    }
}

 

Jan 20 - Search a 2D array; 2D Array; Binary Search;

原文:http://www.cnblogs.com/5683yue/p/5147104.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!