zoukankan      html  css  js  c++  java
  • Search a 2D Matrix

    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 from left to right.
    • The first integer of each row is greater than the last integer of the previous row.

    For example,

    Consider the following matrix:

    [
      [1,   3,  5,  7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    

    Given target = 3, return true.

    思路:
    两次二分搜索,先二分搜索第一列,找出target所在的行,然后二分搜索该行。

     1 public class Solution {
     2     public boolean searchMatrix(int[][] matrix, int target) {
     3         int row = matrix.length;
     4         if(row == 0) return false;
     5         int col = matrix[0].length;
     6         if(col == 0) return false;
     7         
     8         if(target < matrix[0][0]) return false;
     9         int start = 0, end = row -1;
    10         while(start <= end){
    11             int mid = (start + end)/2;
    12             if(matrix[mid][0] ==target)
    13                 return true;
    14             else if(matrix[mid][0] < target)
    15                 start = mid +1;
    16             else
    17                 end = mid-1;
    18         }
    19         
    20         int targetRow = end;
    21         start = 0;
    22         end = col-1;
    23         while(start <= end){
    24              int mid = (start + end)/2;
    25             if(matrix[targetRow][mid] ==target)
    26                 return true;
    27             else if(matrix[targetRow][mid] < target)
    28                 start = mid +1;
    29             else
    30                 end = mid-1;
    31         }
    32         return false;
    33     }
    34 }
  • 相关阅读:
    封装tip控件
    Javascirpt中创建对象的几种方式
    使用Servlet上传文件
    Struts2 基本配置
    使用JQuery实现手风琴布局
    winform下自绘提示框风格窗体
    环形进度条
    Oracle中获取当前时间半小时前的时间
    JSTL+MyEclipse8.5+Tomcat配置
    使用CSS和jQuery实现对话框
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3540018.html
Copyright © 2011-2022 走看看