LeetCode 74 Search a 2D Matrix (Search 2D Matrix)
Translation
Write an efficient algorithm to find a value in a matrix of m x n. This matrix has the following attributes: the integer numbers of each row are sorted from left to right. The first element of each row is larger than the last column of the previous row. For example, consider the following matrices: [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] returns true if target = 3 is specified.
Original
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.
Analysis
It may be because I am so sleepy, so the efficiency is very low for both the algorithm and myself ......
The following code is also changed ......
bool searchMatrix(vector
>& matrix, int target) { if (matrix[0][0] > target) return false; for (int i = 0; i < matrix.size(); ) { for (int j = 0; j < matrix[i].size(); ) { if (i == matrix.size() - 1 && matrix[i][j] < target) { if (j >= matrix[i].size()) return false; j += 1; if (matrix[i][j] > target) return false; } else if (matrix[i][j] < target && matrix[i+1][j] > target) { j += 1; if (j >= matrix[i].size()) return false; if (matrix[i][j] > target) return false; } else if (matrix[i][j] < target && matrix[i + 1][j] <= target) { i += 1; } else if (matrix[i][j] == target) { return true; } if (i == matrix.size() - 1 && j == matrix[i].size() ) { return false; } } } return false;}
Sort out your ideas and try again tomorrow ......