leetcode 240. Search a 2D Matrix II 搜索二维矩阵 II(中等)
2023-09-11 14:22:52 时间
一、题目大意
标签:数组
https://leetcode.cn/problems/search-a-2d-matrix-ii
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
示例 1:
输入: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
输出:true
示例 2:
输入: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
输出:false
提示:
- m == matrix.length
- n == matrix[i].length
- 1 <= n, m <= 300
- -109 <= matrix[i][j] <= 109
- 每行的所有元素从左到右升序排列
- 每列的所有元素从上到下升序排列
- -109 <= target <= 109
二、解题思路
解题技巧:从右上角开始查找,若当前值大于待搜索值,向左移动一位,若当前值小于待搜索值,向下移动一位。如果最终移动到左下角时仍不等于待搜索值,则说明待搜索值不存在于矩阵中。
三、解题方法
3.1 Java实现
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
// 从右上角开始搜索,比target大就向左移,比target小就向下移
int x = matrix.length - 1;
int y = 0;
while (x >=0 && y < matrix[0].length) {
if (matrix[x][y] == target) {
return true;
} else if (matrix[x][y] > target) {
x--;
} else {
y++;
}
}
return false;
}
}
四、总结小记
- 2022/8/5 疫情啊,什么时候能消停一会
相关文章
- JS Leetcode 74. 搜索二维矩阵题解分析,二分法与坐标轴法
- [LeetCode] Populating Next Right Pointers in Each Node
- [LeetCode]面试题10- II. 青蛙跳台阶问题
- LeetCode 33. 搜索旋转排序数组
- 【leetcode】108:将有序数组转化为二叉搜索树
- [LeetCode] 1305. All Elements in Two Binary Search Trees 两棵二叉搜索树中的所有元素
- [LeetCode] 510. Inorder Successor in BST II 二叉搜索树中的中序后继节点之二
- [LeetCode] Search in a Sorted Array of Unknown Size 在未知大小的有序数组中搜索
- [LeetCode] 650. 2 Keys Keyboard 两键的键盘
- [LeetCode] 538. Convert BST to Greater Tree 将二叉搜索树BST转为较大树
- [LeetCode] 450. Delete Node in a BST 删除二叉搜索树中的节点
- [LeetCode] 99. Recover Binary Search Tree 复原二叉搜索树
- [LeetCode] 132. Palindrome Partitioning II 拆分回文串之二
- [LeetCode] 111. Minimum Depth of Binary Tree 二叉树的最小深度
- leetcode 680. Valid Palindrome II 验证回文字符串 Ⅱ
- leetcode算法235.二叉搜索树的最近公共祖先