leetcode--Search a 2D Matrix
来源:互联网 发布:软件开发工程师 编辑:程序博客网 时间:2024/06/10 05:14
题目
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:1.Integers in each row are sorted from left to right.2.The first integer of each row is greater than the last integer of the previous row.
解法1:有序数组的折半查找
先找出target属于哪一行,然后在此行中进行查找
public boolean searchMatrix(int[][] matrix, int target) { if(matrix.length == 0 || matrix[0].length == 0) return false; int start = 0, end = matrix.length-1; if(target < matrix[start][0] || target > matrix[matrix.length-1][matrix[0].length-1]) return false; if(target >= matrix[end][0]) start = end; else{ while(end - start > 1){ int mid = (end + start)/2; if(target >= matrix[mid][0] && target < matrix[end][0]) start = mid; else end = mid; } } int row = start; start = 0; end = matrix[0].length-1; while(start <= end){ int mid = (start+end)/2; if(target < matrix[row][mid]) end = mid - 1; else if(target > matrix[row][mid]) start = mid + 1; else return true; } return false; }
解法2
将二维矩阵看作是一维数组,进行折半查找
对应关系:
m*n matrix[i][j] == array[i*n + j]
array[x] == matrix[x/n][x%n]
折半查找
public boolean searchMatrix(int[][] matrix, int target) { if(matrix.length == 0 || matrix[0].length == 0) return false; int m = matrix.length,n = matrix[0].length; int l = 0,r = m*n - 1; while(l < r){ int x = (l + r)/2; if(matrix[x/n][x%n] == target) return true; else if(matrix[x/n][x%n] <= target) l = x + 1; else r = x - 1; } return matrix[l/n][l%n] == target; }
阅读全文
0 0
- [leetcode][Search] Search a 2D Matrix
- LeetCode: Search a 2D Matrix
- LeetCode Search a 2D Matrix
- [Leetcode] Search a 2D Matrix
- LeetCode : Search a 2D Matrix
- [LeetCode] Search a 2D Matrix
- Leetcode 74 Search a 2D Matrix
- leetcode 90: Search a 2D Matrix
- [LeetCode]Search a 2D Matrix
- [Leetcode] Search a 2-D matrix
- [Leetcode]Search a 2D Matrix
- [leetcode]Search a 2D Matrix
- LeetCode-Search a 2D Matrix
- [leetcode] Search a 2D Matrix
- LeetCode - Search a 2D Matrix
- LeetCode:Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- leetcode之Search a 2D Matrix
- 详解spl_autoload_register()函数
- 网络请求工具类HttpUtil
- 工具类 把一个字节流转成字符串
- Linux SVN 启动
- 「网络流 24 题」餐巾计划
- leetcode--Search a 2D Matrix
- 【队内胡策】2017.10.16
- centos7下使用yum安装mysql5.7.10
- js获取地址栏参数的值
- Jquery validate验证表单时多个name相同的元素
- python-mysql安装错误问题
- Angularjs自定义服务~使用Module的provider方法
- Decorator Design Pattern
- myeclipes mac版下载与破解