LeetCode 74. Search a 2D Matrix
来源:互联网 发布:淘宝优惠券采集软件 编辑:程序博客网 时间:2024/05/24 06:13
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
.
在一个有序的二维数组里面查找一个值,思路是先对行二分查找,再对这行二分查找,不过我的代码只二分查找了行,遍历了这一行也能AC。。
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix.length==0||matrix[0].length==0)return false; int row = matrix.length-1; int col = matrix[0].length-1; int l = 0; int r = row; int m = (l+r)/2; int c = 0; while(l<=r){ if(matrix[m][0]>target&&m!=0&&matrix[m-1][0]<=target){ c = m-1; break; } if(matrix[m][col]<target&&m!=row&&matrix[m+1][col]>=target){ c = m+1; break; } if(matrix[m][0]>target){ r = m-1; m = (l+r)/2; } else{ l = m+1; m = (l+r)/2; } } for(int i=0;i<=col;i++){ if(matrix[c][i]==target)return true; } 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
- 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
- [leetcode] 74. Search a 2D Matrix
- Python学习笔记(五)——日期和时间
- 常用的正则表达式
- android的多点触摸效果
- 2017.7.8~2017.7.9总结
- 数据库金额方面存储
- LeetCode 74. Search a 2D Matrix
- JavaScript 基础知识
- 笔记:新手的Hive指南
- 单词数
- HDU4055 (dp计数)
- DLL重载
- summernote上传图片到本地服务器(node.js)
- HDU1166敌兵布阵&POJ 3468 A Simple Problem with Integers题解
- CMake 入门实战(转)