240. Search a 2D Matrix II
package LeetCode_240 /** * 240. Search a 2D Matrix II * https://leetcode.com/problems/search-a-2d-matrix-ii/description/ * * 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 in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example: Consider the following 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] ] Given target = 5, return true. Given target = 20, return false. * */ class Solution { fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean { if (matrix.isEmpty() || matrix[0].isEmpty()) { return false } //定义两个指针 x and y;x指向第0行,y指向最大的列,开始时指向右上角元素 var x = 0 var y = matrix[0].size - 1 while (true) { if (matrix[x][y] == target) { return true } else if (matrix[x][y] < target) { //表示要找下一行 x++ } else { //表示向左找 y-- } //check the border if (x >= matrix.size || y < 0) { break } } return false } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)