欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

74. Search a 2D Matrix

程序员文章站 2022-03-08 11:35:27
...

题目叙述:

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.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:

Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false

题目分析:

  • 对一个二维矩阵进行使用二分查找,先将其计算所有元素的总数,以拉平。
  • 对一个扁平结构索引编号进行除以列数可以得到该扁平索引对应的二维矩阵的行号,对列数进行取余可以得到对应的列号
  • 该矩阵从左到右从上到下是依次递增的

代码:

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        //对一个二维矩阵进行使用二分查找,先将其计算所有元素的总数,以拉平。
        //对一个扁平结构索引编号进行除以列数可以得到该扁平索引对应的二维矩阵的行号,对列数进行取余可以得到对应的列号
        //该矩阵从左到右从上到下是依次递增的   
        int m = matrix.length;
        if(m==0) return false;
        int n = matrix[0].length;
        int len = m *n;
        int left = 0;
        int right = len-1;
        while(left<=right){
            int mid = left + (right-left)/2;
            int value = matrix[mid/n][mid%n];
            if(value == target) return true;
            else if(value < target) left = mid+1;
            else right = mid-1;
        }
       return false;  
    }
}

相关标签: leetcode题解