博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Search a 2D Matrix II
阅读量:7251 次
发布时间:2019-06-29

本文共 1352 字,大约阅读时间需要 4 分钟。

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.

The same with Lintcode:

O(M+N) time and O(1) Space

1 public class Solution { 2     public boolean searchMatrix(int[][] matrix, int target) { 3         int m = matrix.length; 4         int n = matrix[0].length; 5         if (matrix==null || m==0 || n==0) return false; 6         int i=0, j=n-1; 7         while (i
=0) { 8 if (matrix[i][j] == target) return true; 9 else if (matrix[i][j] > target) {10 j--;11 }12 else i++;13 }14 return false;15 }16 }

 Follow Up: 还有没有什么优化

四分法:我先说了下四分法的想法。先和左上角矩形的右下角比,如果比它大就搜三个的矩阵,否则搜另外三个矩阵。

T(N)= 3T(N/4) +  O(1)

(nm)^(log_{4}^{3})

她接着问有啥别的优化。我问她有没有可能多次询问,有可能的话用一个hash来存下以前的所有解,方便重复询问时直接判断。但是这样空间复杂度有提升。(时间优化的时候,尽量想用空间换时间)

mem:O(1) -> O(t)

她想要的优化是对于一个矩阵的最后一行做二分搜索后,删掉前几列和最后一行,得到一个子矩阵。重复这样的操作,时间复杂度是O(min(m,n)log(max(m,n)))。之后跟她提了一下这个方法在m和n相差比较大的时候可能比较有用。

转载地址:http://pnhbm.baihongyu.com/

你可能感兴趣的文章
Lambda
查看>>
springboot 测试类
查看>>
利用javapns对IOS进行推送
查看>>
求1+2+3+...+n
查看>>
TeX教程
查看>>
C# DataTable 通过Linq分组
查看>>
bzoj 4484 [Jsoi2015]最小表示——bitset
查看>>
问题 C: A+B Problem II
查看>>
react踩坑 - 1, componentDidMount使用
查看>>
busybox microcom
查看>>
hdu6376 度度熊剪纸条 思维
查看>>
二维数组转换成一维数组
查看>>
API 3个 js对象
查看>>
NUC1178 Kickdown
查看>>
理解和运用javascript中的call及apply
查看>>
VUE-CLI 设置页面title
查看>>
微信备份方法
查看>>
微软商业服务器部署系列3-windows serevr 2008介绍
查看>>
UVA 10564 Paths through the Hourglass(背包)
查看>>
[hdu6437]Problem L. Videos
查看>>