图解 leetCode 74.Search a 2D Matrix(搜索二维矩阵)

来源:互联网 发布:易语言制作下载器源码 编辑:程序博客网 时间:2024/06/08 02:22

  最近这段时间一直在搞算法这块,今天搞了几道二分查找的题,下面通过图解的形式分析一下搜索二维矩阵这道题,这道题难道不大,但是可以有不同的解法,我在参考ethannnli博客代码的基础上给出基于二分查找思想的迭代法和递归法两种方法,原博客只给出了迭代法的解法,我补充一个递归法的解法。
  
  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 SearchMatrix {    //迭代解法    public boolean searchMatrix(int[][] nums, int target){        int rowLen = nums.length;        int colLen = nums[0].length;        int min = 0;        int max = rowLen * colLen - 1;        while (min <= max) {            int mid = (min + max)/2;            int row = mid / colLen;            int col = mid % colLen;            //如果nums[row][col] > target, 左边搜索            if (nums[row][col] > target) {                max = mid - 1;            }else if (nums[row][col] < target) {                min = mid + 1;            }else {                return true;            }        }        //如果没有找到返回false        return false;    }    //递归解法    public boolean searchMatrixII(int[][] nums, int target){        int rowLen = nums.length;        int colLen = nums[0].length;        boolean res = search(nums, 0, rowLen * colLen - 1, target);        return res;    }    private boolean search(int[][] nums, int min, int max, int target) {        if (min > max) {            return false;        }        int mid = (min + max)/2;        int colLen = nums[0].length;        int row = mid / colLen;        int col = mid % colLen;        if (nums[row][col] > target) {            return search(nums, min, mid - 1, target);        }else if (nums[row][col] < target) {            return search(nums, mid + 1, max, target);        }else {            return true;        }    }    public static void main(String[] args) {        int[][] nums = {                {1,   3,  5,  7},                {10, 11, 16, 20},                {23, 30, 34, 50}        };        int target = 16;        SearchMatrix searchMatrix = new SearchMatrix();        boolean res = searchMatrix.searchMatrix(nums, target);        System.out.println("能否找到目标值" + target + "?" + res);        boolean res2 = searchMatrix.searchMatrixII(nums, target);        System.out.println("能否找到目标值" + target + "?" + res2);    }

这里写图片描述
  运行结果都是正确的,如果有什么地方写的不对,希望大家指出,相互交流,共同进步!

阅读全文
0 0
原创粉丝点击