个人记录-LeetCode 74. Search a 2D Matrix
来源:互联网 发布:绿地控股历史价格数据 编辑:程序博客网 时间:2024/06/03 22:43
问题:
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,找到合适的行;
然后对该行进行二分法查找即可,主要是注意细节吧。
代码示例:
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length < 1 || matrix[0].length < 1) { return false; } int rowNum = matrix.length; int targetLine = -1; for (int i = 0; i < rowNum; ++i) { //比较第一列,相等则直接返回 if (matrix[i][0] == target) { return true; //否则找到大于target的行 } else if (matrix[i][0] > target) { targetLine = i; break; } } int colNum = matrix[0].length; //没有找到大于target的行 if (targetLine == -1) { //判断最后一个数是否大于等于target if (matrix[rowNum-1][colNum-1] == target) { return true; } else if (matrix[rowNum-1][colNum-1] > target) { return middleSearch(matrix[rowNum-1], target); } else { //最后一个数都小于target,return false return false; } } else if (targetLine >= 1){ return middleSearch(matrix[targetLine-1], target); } else { //第一个数都大于target,return false return false; } } //其它的情况,二分法即可 private boolean middleSearch(int[] matrix, int target) { int begin = 0; int end = matrix.length - 1; while (begin <= end) { int middle = (begin + end) / 2; if (matrix[middle] == target) { return true; } else { if (matrix[middle] > target) { end = middle - 1; } else { begin = middle + 1; } } } return false; }}
0 0
- 个人记录-LeetCode 74. Search a 2D Matrix
- LeetCode 74. Search a 2D Matrix
- [LeetCode]74.Search a 2D Matrix
- LeetCode --- 74. Search a 2D Matrix
- [Leetcode] 74. Search a 2D Matrix
- [leetcode] 74.Search a 2D Matrix
- Leetcode 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix LeetCode
- [LeetCode]74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- LeetCode 74. Search a 2D Matrix
- LeetCode 74. Search a 2D Matrix
- LeetCode *** 74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- LeetCode 74. Search a 2D Matrix
- leetcode-74. Search a 2D Matrix
- HTTP学习笔记:HTTP首部字段(1)
- [Linux]进程之间的管道通信
- 缓存不一致问题
- 未能加载包“Microsoft SQL Server Data Tools”
- 逻辑回归中sigmoid函数的来历
- 个人记录-LeetCode 74. Search a 2D Matrix
- BZOJ1500: [NOI2005]维修数列
- iOS 书写高质量代码 怎么处理耦合关系
- (OK) usbip-utils - usbip attach - usbip detach
- php数组
- 14My2.0版本聊天系统(服务器selector移植)
- PHP - FPM信号机制
- 欢迎使用CSDN-markdown编辑器
- 快速发布局域网WEB地图的方法