LeetCode——Search a 2D Matrix II
2015-09-30 20:47
411 查看
Description:
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
Given target =
Given target =
首先想到的就是遍历整个矩阵,时间复杂度是O(m*n),肯定是Timeout。
然后在优化的话就想到了二分。对每一行进行二分。时间复杂度是O(n*logm),还是Timeout,二分用的越多时间复杂度就越高,所以行列都二分(有点递归分治的意思)更会Timeout。
这么看来时间复杂度必须在线性的基础上才行。观察一下矩阵不难发现把矩阵逆时针旋转45度类似一棵二叉查找树。所以就可以模仿二叉查找树的方法来做了。
这样的话时间复杂度就是O(m + n);AC。
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ]
Given target =
5, return
true.
Given target =
20, return
false.
首先想到的就是遍历整个矩阵,时间复杂度是O(m*n),肯定是Timeout。
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { for(int i=0; i<matrix.length; i++) { for(int j=0; j<matrix[i].length; j++) { if(matrix[i][j] == target) { return true; } } } return false; } }
然后在优化的话就想到了二分。对每一行进行二分。时间复杂度是O(n*logm),还是Timeout,二分用的越多时间复杂度就越高,所以行列都二分(有点递归分治的意思)更会Timeout。
public class Solution { public boolean binarySearch(int[] arr, int terget) { int left = 0, int right = arr.length - 1; while(left <= right) { int mid = left + (right - left) / 2; if(target == arr[mid]) { return true; } if(target > arr[mid]) { left = mid + 1; } else { right = mid - 1; } } return false; } public boolean searchMatrix(int[][] matrix, int target) { for(int i=0; i<matrix.length; i++) { if(binarySearch(matrix[i], target)) { return true; } } return false; } }
这么看来时间复杂度必须在线性的基础上才行。观察一下矩阵不难发现把矩阵逆时针旋转45度类似一棵二叉查找树。所以就可以模仿二叉查找树的方法来做了。
这样的话时间复杂度就是O(m + n);AC。
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix.length==0 || matrix[0].length==0) { return false; } int i = 0, j = matrix[0].length - 1; while(i < matrix.length && j >= 0) { int cur = matrix[i][j]; if(cur == target) { return true; } else if(cur < target) { i ++; } else { j --; } } return false; } }
相关文章推荐
- [置顶] 【动态规划】求最长公共子串,最长回文子串
- 博客中插入公式——之在线数学公式生成
- iOS之字符串拼接
- ios- 地图路线规划
- find the most comfortable road
- NSDate
- [置顶] 【动态规划】求最长公共子序列
- 脑网络基础
- 第三次作业——计划书导入功能的实现
- c中文件的读取操作
- UI高级第四课 iOS绘图与动画——iOS学习连载32
- LintCode -- 二叉树的中序遍历
- 云计算(2)-Cloud是什么
- Java数据结构与算法之数组应用——用户登陆与注册数组实现
- 分布式一致性协议Raft原理与实例
- [置顶] 【动态规划】求一维子数组的最大和
- poj1780
- 分布式一致性协议Raft原理与实例
- 探究float类型参数的传递方式
- Java文件操作2