[牛客网-Leetcode] #Find#Array Medium search-a-2d-matrix

Find the target value in the sorted two-dimensional matrix search-a-2d-matrix

Title description

Please write an efficient algorithm for judging whether the target value exists in the m*n matrix. The matrix has the following characteristics:
the numbers in
each row are sorted from left to right , and the first number in each row is greater than the last number in the previous row
For example:
for the following matrix:
[↵ [1, 3, 5, 7],↵ [10, 11, 16, 20],↵ [23, 30, 34, 50]↵]
The target value to be searched is 3, Return true;

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, returntrue.

Example

enter

[[1,1]],0

Output

false

Problem-solving ideas

  • After the two-dimensional array is expanded, it is equivalent to a sorted one-dimensional array, and the binary search method can be used to find the target value.
class Solution {
    
    
public:
    bool searchMatrix(vector<vector<int> >& matrix, int target) {
    
    
        if(matrix.size() == 0 || matrix[0].size() == 0) {
    
    
            return false;
        }
        int m = matrix.size(), n = matrix[0].size();
        int left = 0, right = m * n - 1;
        while(left <= right) {
    
    
            //二维数组中从左往右,从上往下依次数的元素序号
            int mid = left + (right - left) / 2;
            //对应到二维数组中的行和列,取出元素
            int temp = matrix[mid / n][mid % n];
            if(temp == target) {
    
    
                return true;
            } else if(temp < target) {
    
    
                left = mid + 1;
            } else if(temp > target) {
    
    
                right = mid - 1;
            }
        }
        return false;
    }
};

Guess you like

Origin blog.csdn.net/cys975900334/article/details/106680154