【LeetCode】 74. Search a 2D Matrix 搜索二维矩阵(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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:
1. Integers in each row are sorted from left to right.
2. The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
题目大意
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
1. 每行中的整数从左到右按升序排列。
2. 每行的第一个整数大于前一行的最后一个整数。
解题方法
1、采用双指针,从第一排的最后一个元素开始
2、matrix[i][j] > target,j–,否则 i++
note: 因为满足:每行的第一个整数大于前一行的最后一个整数。
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0 || matrix[0].length == 0) return false;
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;
}
}
执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 42.2 MB, 在所有 Java 提交中击败了 21.22% 的用户