【LeetCode】240. Search a 2D Matrix II 搜索二维矩阵 II(Medium)(JAVA)
题目地址: https://leetcode.com/problems/search-a-2d-matrix-ii/
题目描述:
Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Example 1:
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
Output: true
Example 2:
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
Output: false
Constraints:
- m == matrix.length
- n == matrix[i].length
- 1 <= n, m <= 300
- -10^9 <= matix[i][j] <= 10^9
- All the integers in each row are sorted in ascending order.
- All the integers in each column are sorted in ascending order.
- -10^9 <= target <= 10^9
题目大意
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
- 每行的元素从左到右升序排列。
- 每列的元素从上到下升序排列。
解题方法
- 采用双指针法,首先指向第一排的最后一个元素
- 如果当前元素大于 target, 只能往前遍历,因为往后和往下都大于当前元素,所以 i–
- 如果当前元素小于 target,只能往下遍历,因为往前和往上都小于当前元素。至于不往后是因为遍历到当前位置,如果是最后一个元素,不能往后;如果不是最后一个元素,肯定是前面往前走了一步,为什么往前走呢?当然是后面的元素大于 target了。所以要么后面没法走,要么后面大于 target,都没必要往后走
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int i = 0;
int j = matrix[0].length - 1;
while (i < matrix.length && j >= 0) {
if (matrix[i][j] == target) return true;
if (matrix[i][j] > target) {
j--;
} else {
i++;
}
}
return false;
}
}
执行耗时:7 ms,击败了44.30% 的Java用户
内存消耗:44.4 MB,击败了21.27% 的Java用户