• 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);
  • 相关阅读:
    SDN网络笔记【毕设-SDN网络】
    Latex笔记【Latex】
    小米路由器 3G 开启SSH 安装 MT 工具箱 【环境搭建,小米路由器】
    windows 下安装linux子系统及其可视化【Linux】
    11月1日数据结构讨论班 【杂】
    简单远程遥控程序【网络程序设计
    VPS使用小结【VPS】
    vim使用总结【Vim】
    域名解析【网络程序设计
    MySQL数据库修改字段名、字段类型、字段长度
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6484050.html
Copyright © 2020-2023  润新知