【leetcode】Array——Search a 2D Matrix(74)
来源:互联网 发布:ps -ef|grep java 编辑:程序博客网 时间:2024/05/22 05:34
题目:
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
0 0
- 【leetcode】Array——Search a 2D Matrix(74)
- LeetCode[Array]: Search a 2D Matrix
- 74. Search a 2D Matrix--Array/LeetCode/C++
- LeetCode刷题【Array】Search a 2D Matrix
- leetcode.array--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】Search a 2D Matrix #74
- LeetCode(74) Search a 2D Matrix
- Leetcode #74 Search a 2D Matrix
- Leetcode #74 Search a 2D Matrix
- leetcode 74: Search a 2D Matrix
- SBA--以服务为基础的架构
- npm 淘宝镜像配置一直无效的可能原因
- 广师Android群分享集合大分类
- typeid typeinfo
- 非参方法-K NearestNeighbor(KNN)
- 【leetcode】Array——Search a 2D Matrix(74)
- 文本深度表示模型Word2Vec
- 排序之冒泡排序
- Linux精讲——chattr特殊权限
- 常用网址
- io流处理文件夹复制功能(java代码)
- 道客巴巴免费复制
- 个人机房重构——组合查询及优化
- Reflect 数组操作示例