LeetCode 74. Search a 2D Matrix
2017-07-10 02:10
423 查看
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:
Given target =
在一个有序的二维数组里面查找一个值,思路是先对行二分查找,再对这行二分查找,不过我的代码只二分查找了行,遍历了这一行也能AC。。
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; } }
相关文章推荐
- 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 搜索一个二维矩阵
- [leetcode-查找]--74. Search a 2D Matrix
- 剑指offer 面试题3:二维数组(矩阵)中数的查找(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_middle_71_74. Search a 2D Matrix