leetcode_middle_71_74. Search a 2D Matrix
2017-03-07 19:17
375 查看
题意:
一个从上到下,从左到右有序的矩阵,要求实现其查找算法。
分析:
意思不就是有序,明显二分查找。由于是二维数组,首先我们就思考能不能按照一维的方法做(先尝试最良好的实现代码风格),把一个数字转化为坐标,比如求余啥的(再继续思考,发现可以)。
我们递归之:
public class Solution {
int row = 0;
int col = 0;
public boolean searchMatrix(int[][] matrix, int target) {
row = matrix.length;
if (row == 0) {
return false;
}
col = matrix[0].length;
return binarySearchMatrix(matrix, 0, row*col-1, target);
}
private boolean binarySearchMatrix(int[][] matrix, int low, int high, int target){
if(low>high){
return false;
}
int mid = low + (high - low)/2;
if(target<matrix[mid/col][mid%col])
return binarySearchMatrix(matrix, low, mid-1, target);
else if(target>matrix[mid/col][mid%col])
return binarySearchMatrix(matrix, mid+1, high, target);
else
return true;
}
}
一个从上到下,从左到右有序的矩阵,要求实现其查找算法。
分析:
意思不就是有序,明显二分查找。由于是二维数组,首先我们就思考能不能按照一维的方法做(先尝试最良好的实现代码风格),把一个数字转化为坐标,比如求余啥的(再继续思考,发现可以)。
我们递归之:
public class Solution {
int row = 0;
int col = 0;
public boolean searchMatrix(int[][] matrix, int target) {
row = matrix.length;
if (row == 0) {
return false;
}
col = matrix[0].length;
return binarySearchMatrix(matrix, 0, row*col-1, target);
}
private boolean binarySearchMatrix(int[][] matrix, int low, int high, int target){
if(low>high){
return false;
}
int mid = low + (high - low)/2;
if(target<matrix[mid/col][mid%col])
return binarySearchMatrix(matrix, low, mid-1, target);
else if(target>matrix[mid/col][mid%col])
return binarySearchMatrix(matrix, mid+1, high, target);
else
return true;
}
}
相关文章推荐
- [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)
- 【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题解c++ | 74. Search a 2D Matrix
- [leetcode] 【查找】 74. Search a 2D Matrix
- Leetcode 74. Search a 2D Matrix
- 【leetcode】74. Search a 2D Matrix【java】