• 240. 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.

    本题目,开始的时候想法是遍历每一行,每一行使用binary search来做,时间复杂度是O(mlongn)。代码如下:

     1 public class Solution {
     2     public boolean searchMatrix(int[][] matrix, int target) {
     3         if(matrix==null||matrix.length==0||matrix[0].length==0) return false;
     4         int m = matrix.length;
     5         int n = matrix[0].length;
     6         for(int i=0;i<m;i++){
     7             int left = 0,right = n-1;
     8             while(left<=right){
     9                 int mid = left+(right-left)/2;
    10                 if(matrix[i][mid]==target) return true;
    11                 else if(matrix[i][mid]<target) left = mid+1;
    12                 else right = mid-1;
    13             }
    14         }
    15         return false;
    16     }
    17 }
    18 //the run time complexity could be O(mlongn), the space complexity could be O(1);

    看了答案才知道原来可以达到O(m+n)来做,代码如下:

     1 public class Solution {
     2     public boolean searchMatrix(int[][] matrix, int target) {
     3         if(matrix==null||matrix.length==0||matrix[0].length==0) return false;
     4         int m = matrix.length;
     5         int n = matrix[0].length;
     6         int row = 0;
     7         int col = n-1;
     8         while(row<m&&col>=0){
     9             if(matrix[row][col]==target) return true;
    10             else if(matrix[row][col]<target&&row<m-1){
    11                 row++;
    12             }else if(matrix[row][col]>target&&col>0){
    13                 col--;
    14             }else{
    15                 break;
    16             }
    17         }
    18         return false;
    19     }
    20 }
    21 //the run time complexity would be O(m+n),the space complexity could be O(1);
  • 相关阅读:
    DOM event beforeload
    有关点击付费的十大失误-转载
    DOM 事件DOMContentLoaded
    Git 系列之四:Git 进阶功能转载
    Qt webkit中单独编译JavaScriptCore
    搜索知识与技巧集锦转载
    webkit中DOM 事件有多少
    Git 系列之三:Windows 下 Git 配置与使用指南转载
    简历:第一章:技术亮点如何写
    实战:第十三章:工作中熬夜加班学到的
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6484050.html
Copyright © 2020-2023  润新知