[leetcode] Search a 2D matrix
2015-02-07 02:57
260 查看
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 =
思路:很容易发现所有数已经排过序,则可以用二分查找,注意将index转化成二维坐标。
public class Solution {
public int[] findpos(int num, int row, int col){
int[] pos = new int[2];
pos[0] = num / col;
pos[1] = num % col;
return pos;
}
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length;
int col = matrix[0].length;
int total = row*col;
int hi = total - 1;
int low = 0;
while(low <= hi){
int mid = (low + hi)/2;
int[] pos = findpos(mid, row, col);
int number = matrix[pos[0]][pos[1]];
if(number == target)
return true;
else if(number < target)
low = mid + 1;
else
hi = mid - 1;
}
return false;
}
}
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.
思路:很容易发现所有数已经排过序,则可以用二分查找,注意将index转化成二维坐标。
public class Solution {
public int[] findpos(int num, int row, int col){
int[] pos = new int[2];
pos[0] = num / col;
pos[1] = num % col;
return pos;
}
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length;
int col = matrix[0].length;
int total = row*col;
int hi = total - 1;
int low = 0;
while(low <= hi){
int mid = (low + hi)/2;
int[] pos = findpos(mid, row, col);
int number = matrix[pos[0]][pos[1]];
if(number == target)
return true;
else if(number < target)
low = mid + 1;
else
hi = mid - 1;
}
return false;
}
}
相关文章推荐
- 【leetCode】Search a 2D Matrix
- 96_leetcode_Search a 2D Matrix
- [LeetCode]Search a 2D Matrix
- LeetCode——Search a 2D Matrix
- leetcode——Search a 2D Matrix 二维有序数组查找(AC)
- leetcode--Search a 2D Matrix
- 第十八周:[leetCode] 74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- 【leetcode】74. Search a 2D Matrix
- LeetCode Search a 2D Matrix
- Leetcode: Search a 2D Matrix
- 个人记录-LeetCode 74. Search a 2D Matrix
- Search a 2D Matrix - LeetCode
- leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法
- leetcode Search a 2D Matrix
- (leetcode)Search a 2D Matrix
- Search a 2D Matrix leetcode
- leetcode 74. Search a 2D Matrix
- 【leetcode】 Search a 2D Matrix (easy)
- leetcode_middle_71_74. Search a 2D Matrix