Search a 2D Matrix

    xiaoxiao2023-03-24  4

    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.

    discussion里的高票解法:https://discuss.leetcode.com/topic/3227/don-t-treat-it-as-a-2d-matrix-just-treat-it-as-a-sorted-list

    把矩阵当成一个排好序的序列,matrix[i][j]=a[i*m+j],其中矩阵大小是n*m的。反过来,a[x]=a[x/m][x%m]。

    class Solution { public: bool searchMatrix(vector > &matrix, int target) { int n = matrix.size(); int m = matrix[0].size(); int l = 0, r = m * n - 1; while (l != r){ int mid = (l + r - 1) >> 1; if (matrix[mid / m][mid % m] < target) l = mid + 1; else r = mid; } return matrix[r / m][r % m] == target; } };

    转载请注明原文地址: https://ju.6miu.com/read-1200875.html
    最新回复(0)