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 }
  • 相关阅读:
    mysql索引类型 normal, unique, full text
    16.信号量互斥编程
    15.信号通信编程
    14.有名管道通信
    13.无名管道通讯编程
    12.多进程程序的操作
    11.进程控制理论
    10.时间编程
    9. 库函数方式文件编程
    8.Linux文件编程
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3540018.html
Copyright © 2011-2022 走看看