zoukankan      html  css  js  c++  java
  • 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相差比较大的时候可能比较有用。

  • 相关阅读:
    U盘为什么还有剩余空间,但却提示说空间不够
    U盘安装系统
    win8 64位+Oracle 11g 64位下使用PL/SQL Developer 的解决办法
    Oracle 去掉重复字符串
    ORACLE获取字符串中数字部分
    MyBatis中的大于、小于、like等符号写法
    Oracle计算时间差函数
    HDU 3569 Imaginary Date 简单期望
    C语言之——文件操作模式
    LeetCode OJ 之 Ugly Number II (丑数-二)
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5060662.html
Copyright © 2011-2022 走看看