【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
题解:直接把二维数组看成一个长度为m*n的数列,然后用二分法查找target,注意在这个数列中编号为k的数在二维数组中的坐标x = k/n, y=k%n;
代码如下;
1 public class Solution { 2 public boolean searchMatrix(int[][] matrix, int target) { 3 if(matrix.length == 0 || matrix[0].length == 0) 4 return false; 5 int m = matrix.length; 6 int n = matrix[0].length; 7 8 int start = 0,end = m*n-1; 9 while(start <= end){ 10 int mid = start + (end-start)/2; 11 int x = mid/n; 12 int y = mid%n; 13 14 if(matrix[x][y] == target) 15 return true; 16 17 if(matrix[x][y] < target) 18 start = mid+1; 19 else 20 end = mid-1; 21 } 22 return false; 23 } 24 }
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了