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 if greater than the last integer of the previous row.
这道题让我们判断给定的数字是否在矩阵中,而且这个矩阵还是非常有规律的:每一行是从小到大排好序的,而且每一行的第一个元素比上一行的最后一个元素大。嘶……这不就相当于是一个排好序的数组吗?作为一名想法非常直接,非常单纯(肯定不是因为我菜)的当代大学生, 我脑海里的第一个想法就是:遍历
解法一:
既然如此,想要判断target这个元素到底在矩阵中存不存在,那我们就逐元素遍历,如果找到了就返回true,否则返回false。同时,因为矩阵中的元素都是排好序的,我们可以加一点点优化,当遍历到的元素值已经大于target时,之后的元素必然不会等于target了,那我们就在这个条件下返回false。
我的实现代码如下:
public class Solution {
public boolean searchMatrix(int[][] matrix, int target