lintcode-搜索二维矩阵 java

题目描述:

 

写出一个高效的算法来搜索 m × n矩阵中的值。

 

 

 

这个矩阵具有以下特性:

 

 

 

  • 每行中的整数从左到右是排序的。
  • 每行的第一个数大于上一行的最后一个整数。

 

代码实现:

public class Solution {
    /*
     * @param matrix: matrix, a list of lists of integers
     * @param target: An integer
     * @return: a boolean, indicate whether matrix contains target
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length==0){
            return false;
        }
        if (matrix[0]==null || matrix[0].length==0){
            return false;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int start = 0;
        int end = row * col - 1;
        while(start <= end){
            
            System.out.println(start);
            
            int mid =  (end + start) / 2;
            int num = matrix[mid/col][mid%col];
            
            if (num==target){
                return true;
            }else if (num > target){
                end = mid-1;
            }else{
                start = mid+1;
            }
        }
        return false;
    }
}

备注:坑死我的一道题,

1.二分查找,其中mid有两种表示形式,一种(end+start)/ 2,一种start+(end-start)/ 2

 

2.知道index求矩阵中元素:用index/col列元素;

 

posted @ 2018-02-04 14:47  果断的荔枝  阅读(89)  评论(0编辑  收藏  举报