zoukankan      html  css  js  c++  java
  • Search a 2D Matrix

    Write an efficient algorithm that searches for a value in an mn 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.
    Example

    Consider the following matrix:

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

    Given target = 3, return true.

    分析


    首先想到的是将二维坐标转换为一维
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    public class Solution {
        /**
         * @param 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) {
            // write your code here
            if(matrix == null || matrix.length == 0 || matrix[0].length == 0return false;
            int row = matrix.length;
            int col = matrix[0].length;
             
            int left = 0, right = row * col - 1;
            while(left < right){
                int mid = left + (right - left) / 2;
                int i = mid / col;
                int j = mid % col;
                if(matrix[i][j] < target){
                    left = mid + 1;
                }
                else{
                    right = mid;
                }
            }
            if(matrix[left / col][left % col] == target)
                return true;
            else
                return false;
        }
    }




  • 相关阅读:
    PyCharm使用(完全图解(最新经典))
    pg存储过程学习
    sql_to_sqlalchemy
    python中嵌入lua解析器
    Python和lua互相调用
    Lupa
    [cb] Unity Editor 添加右键菜单
    [C#] 委托之Action和Func区别
    [反编译U3D]Decompile Unity Resources
    [cb] Assetbundle打包(一)
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/846d7638ae056782cddff06368ece5c6.html
Copyright © 2011-2022 走看看