• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Search a 2D Matrix II

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: Search a 2D Matrix II

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<m && j>=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相差比较大的时候可能比较有用。

posted @ 2015-12-20 12:42  neverlandly  阅读(247)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3