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:

[
[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; } }

最新文章

  1. ASP.NET MVC 4+ T.JPager使用
  2. centos7下安装vsftpd与PAM虚拟用户
  3. (转) mysql的连接,创建账号,修改密码
  4. system函数
  5. Eclipse reports that Android SDK Content Loader has encountered a problem. parseSdkContent failed.
  6. java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.L(转)
  7. HighlightingSystem插件使用(边缘发光)
  8. python 【第三篇】:函数及参数
  9. CSS三角形制作样式
  10. ZOJ 3923 Handshakes
  11. 利用 Traceview 精准定位启动时间测试的异常方法 (工具开源)
  12. Sequence query 好题啊
  13. OpenCV计算物体的重心坐标(2值图像)
  14. Python内置函数(65)——type
  15. UITableView section 圆角 阴影
  16. &lt;a&gt;标签里的函数事件写法的实战建议
  17. activeMq-2 高可用以及集群搭建
  18. SSH, 整合分页功能,连带DAO经典封装
  19. HTML 5 Canvas vs. SVG
  20. 3.1-uC/OS-III的特点:

热门文章

  1. Android——TextView属性XML详解
  2. Yii CDbCriteria 常用方法
  3. IE6、IE7、IE8、Firefox兼容性
  4. C#中对 XML节点进行添加,删除,查找和删除操作
  5. java-事务-案例
  6. java-jdbc循环设置sql参数
  7. Linux C定时器使用指南
  8. js学习笔记21----表格操作
  9. 關於 WebClient wc = new WebClient() 下載第三方數據不能進安安信任異常
  10. 使用 jQuery UI 和 jQuery 插件构建更好的 Web 应用程序