【leetcode刷题笔记】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 is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
题解:每次用右上角的元素跟target比较,有三种情况:
- 相等,说明找到了target;
- 右上角元素比target元素大,那么说明target在第一行,递归的搜索第一行。
- 右上角元素比target元素小,那么说明target在第二行及以后,递归的搜索如下图所示区域:
代码如下:
1 public class Solution { 2 private boolean IfFind = false; 3 private void RightCornerRecur(int[][] matrix,int target,int m_start,int m_end,int n_start,int n_end){ 4 if(m_start > m_end || n_start > n_end) 5 return; 6 7 if(m_start < 0 || n_start < 0 || m_end >= matrix.length || n_end >= matrix[0].length) 8 return; 9 10 if(matrix[m_start][n_end] == target){ 11 IfFind = true; 12 return; 13 } 14 if(matrix[m_start][n_end] > target) 15 RightCornerRecur(matrix, target, m_start, m_start, n_start, n_end-1); 16 else { 17 RightCornerRecur(matrix, target, m_start+1,m_end, n_start, n_end); 18 } 19 20 } 21 public boolean searchMatrix(int[][] matrix, int target) { 22 RightCornerRecur(matrix, target,0,matrix.length-1, 0, matrix[0].length-1); 23 return IfFind; 24 } 25 }
右上角可以用来比较剪掉一些元素,左下角同样可以,下面的代码中加上了左下角元素与target元素的比较,最终的运行时间是384ms,而上述只考虑右上角的运行时间是472ms。
1 public class Solution { 2 private boolean IfFind = false; 3 private void RightCornerRecur(int[][] matrix,int target,int m_start,int m_end,int n_start,int n_end){ 4 5 if(m_start > m_end || n_start > n_end) 6 return; 7 8 if(m_start < 0 || n_start < 0 || m_end >= matrix.length || n_end >= matrix[0].length) 9 return; 10 11 12 if(matrix[m_start][n_end] == target){ 13 IfFind = true; 14 return; 15 } 16 17 if(matrix[m_start][n_end] > target) 18 RightCornerRecur(matrix, target, m_start, m_start, n_start, n_end-1); 19 20 else { 21 if(matrix[m_end][0] == target){ 22 IfFind = true; 23 return; 24 } 25 if(matrix[m_end][0] < target) 26 RightCornerRecur(matrix, target, m_end, m_end, n_start+1, n_end); 27 else 28 RightCornerRecur(matrix, target, m_start+1,m_end-1, n_start, n_end); 29 } 30 31 } 32 public boolean searchMatrix(int[][] matrix, int target) { 33 RightCornerRecur(matrix, target,0,matrix.length-1, 0, matrix[0].length-1); 34 return IfFind; 35 } 36 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了