已解决
leetcode top100(20) 搜索二维矩阵 II
来自网友在路上 166866提问 提问时间:2023-09-25 09:56:13阅读次数: 66
最佳答案 问答题库668位专家为你答疑解惑
编写一个高效的算法来搜索 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
package TOP11_20;/*** * 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:** 每行的元素从左到右升序排列。* 每列的元素从上到下升序排列。* */
public class Top19 {public static boolean searchMatrix(int[][] matrix, int target) {if (matrix.length == 0) {return false;}int rowLength = matrix.length;int colHeight = matrix[0].length;int row = 0;int col = colHeight - 1;// 从矩阵右上角看 右上角值>target 那么就减少列大小,数值再进行对比,右上角值<target,那么行增加,数值增大在进行对比while (row < rowLength && col >= 0) {if (matrix[row][col] < target) {row++;} else if (matrix[row][col] > target) {col--;} else {return true;}}return false;}public static void main(String[] args) {int[][] nums ={{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}};System.out.println(searchMatrix(nums,20));}
}
harryptter / LeetcodeTop100 · GitCode
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"leetcode top100(20) 搜索二维矩阵 II":http://eshow365.cn/6-13386-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: Tomcat的安装与使用
- 下一篇: MYSQL——命令大全