[leetcode] 74. 搜索二维矩阵

题目分析

这个题目是一维二分法的变形.

link

http://www.cnblogs.com/acbingo/p/9374587.html

python 代码

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        # guard clause
        if len(matrix) == 0:
            return False
        m = len(matrix)
        n = len(matrix[0])
        
        low = 0
        high = m*n-1
        # 边界条件 low>high
        while low<=high:
            # mid 采用下中位数
            mid = low + (high-low)/2
            row = mid/n
            col = mid%n
            if(matrix[row][col]> target):
                high = mid -1
            elif(matrix[row][col]<target):
                low = mid+1
            else:
                return True
        return False

java 代码

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length;
        if (m == 0) {
            return false;
        }
        int n = matrix[0].length;
        if (n==0){
            return false;
        }
        int cnt = m * n;
        if (target > matrix[m - 1][n - 1]) {
            return false;
        }
        if (target < matrix[0][0]) {
            return false;
        }


        int l = 0;
        int r = cnt - 1;
        int mid = (l + r) / 2;
        while (l <= r) {
            if (get(matrix, mid, m, n) == target) {
                return true;
            }
            if (get(matrix, mid, m, n) > target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
            mid = (l + r) / 2;
        }
        return false;

    }

    // 返回矩阵中的第i个数
    int get(int[][] matrix, int i, int m, int n) {
        int p = i / n;
        int q = i % n;
        return matrix[p][q];

    }
}
    原文作者:cptn3m0
    原文地址: https://www.jianshu.com/p/a87cff8794fa
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞