leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法

Posted liguangsunls

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法相关的知识,希望对你有一定的参考价值。

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

思路:此题还是比較简单的。主要是用两个二分法,才对第一列使用,再对特定的行使用。

详细代码例如以下:

public class Solution {
    public boolean searchMatrix(int[][] m, int target) {
        //两个二分搜索
        //先搜索第一列,找到确定的行,然后再搜索行
        int i = 0;
        int j = m.length-1;
        int mid = 0;
        //搜寻第一列
        while(i <= j){
            mid = (i + j)/2;
            if(m[mid][0] == target){
                return true;
            }else if(m[mid][0] < target){
                i = mid + 1;
            }else{
                j = mid - 1;
            }
        }
        if(m[mid][0] > target){
            if(mid == 0){
                return false;
            }
            mid--;//mid-1
        }
        //搜寻mid行
        i = 0;
        j = m[0].length -1;
        int k = mid;
        //搜寻到了返回true
        while(i <= j){
            mid = (i + j)/2;
            if(m[k][mid] == target){
                return true;
            }else if(m[k][mid] < target){
                i = mid + 1;
            }else{
                j = mid - 1;
            }
        }
        //没有搜寻到,返回false
        return false;
    }
}




以上是关于leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 74 Search a 2D Matrix ----- java

LeetCode 74.Search a 2D Matrix Java

19.2.13 [LeetCode 74] Search a 2D Matrix

[LeetCode] 74. Search a 2D Matrix 搜索一个二维矩阵

leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法

LeetCode 74 Search a 2D Matrix(搜索2D矩阵)