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;
        }
    }




  • 相关阅读:
    Linux查看占用内存前10的命令
    使用RestTemplate调用SpringCloud注册中心内的服务
    Eureka集群配置
    MySQL常用命令集合(偏向运维管理)
    pytest: error: unrecognized arguments报错解决
    MongoDB的安装
    MongoDB多条件分组聚合查询
    在排序数组中查找元素的第一个和最后一个位置
    搜索二维矩阵
    搜索旋转排序数组
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/846d7638ae056782cddff06368ece5c6.html
Copyright © 2011-2022 走看看