zoukankan      html  css  js  c++  java
  • 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;
        }
    }


  • 相关阅读:
    [SCOI2009] Windy数
    [P1361] 小M的作物
    Wannafly Camp 2020 Day 2E 阔力梯的树
    2017百越杯反序列化writeup
    大美西安writeup
    Thinkphp的SQL查询方式
    Thinkphp的CURD
    记一次拿webshell踩过的坑(如何用PHP编写一个不包含数字和字母的后门)
    ThinkPHP的输出和模型使用
    ThinkPHP的运行流程-2
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/6891575.html
Copyright © 2011-2022 走看看