【leetcode】Array——Search a 2D Matrix(74)
2016-02-27 17:04
375 查看
题目:
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 =
思路:两次binary search,第一次查询第一列,判断target可能出现在哪一行,然后再binary search该行。
第一次提交没过,因为没有考虑到如果target<matrix[0][0],第一次binary search后确定的行会是-1,导致后面ArrayIndexOutOfBoundsException:
-1
代码:
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.
思路:两次binary search,第一次查询第一列,判断target可能出现在哪一行,然后再binary search该行。
第一次提交没过,因为没有考虑到如果target<matrix[0][0],第一次binary search后确定的行会是-1,导致后面ArrayIndexOutOfBoundsException:
-1
代码:
public boolean searchMatrix(int[][] matrix, int target) { int rows=matrix.length; if(rows==0) return false; int lines=matrix[0].length; //search first element of each row int up=0,down=rows-1; while(up<=down){ int mid = up + ((down-up)>>1); if(matrix[mid][0]==target) return true; if(target<matrix[mid][0]) down=mid-1; else up=mid+1; } if(down==-1) return false; //search the row int left=0,right=lines-1; while(left<=right){ int mid = left+((right-left)>>1); if(matrix[down][mid]==target) return true; if(target<matrix[down][mid]) right=mid-1; else left=mid+1; } return false; }改进:不要把matrix看成是二维数组
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0) { return false; } int start = 0, rows = matrix.length, cols = matrix[0].length; int end = rows * cols - 1; while (start <= end) { int mid = (start + end) / 2; if (matrix[mid / cols][mid % cols] == target) { return true; } if (matrix[mid / cols][mid % cols] < target) { start = mid + 1; } else { end = mid - 1; } } return false; } }leetcode链接:https://leetcode.com/discuss/10735/dont-treat-it-as-a-2d-matrix-just-treat-it-as-a-sorted-list
相关文章推荐
- C语言:未包含头文件引起的奇怪错误
- 文本深度表示模型Word2Vec
- Android 高清加载巨图方案 拒绝压缩图片
- [Hapi.js] Up and running
- 广师Android群分享集合大分类
- Demo7:背景截取图标显示
- C++中的ostringstream、istringstream和getline()
- Bitmap图片缩放处理
- xtrabackup
- spring 整合jackson
- html5标签总结
- 【SPOJ DISUBSTR】Distinct Substrings 后缀数组
- POJ 1129 Channel Allocation DFS+四色定理
- 微信调用扫一扫的步骤
- Android项目使用兼容包(support v7)
- 005_Http之request获取客户端信息03-获取请求参数
- 【转】Linux下的多线程编程
- leetcode-98
- Solr(二)
- DataGridView 在下拉框添加下来事件