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

    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.

     1 public class Solution {
     2     public boolean searchMatrix(int[][] matrix, int target) {
     3         int m = matrix.length, n = matrix[0].length;
     4         if(m == 0 || n == 0) return false;
     5         int i = m-1,j = 0;
     6         while(i >= 0 && j < n){
     7             if(matrix[i][j] == target) return true;
     8             if(matrix[i][j] > target) i--;
     9             else j++;
    10         }
    11         return false;
    12     }
    13 }

    该题矩阵也是有特点的。 对比题目:

    http://www.cnblogs.com/guoguolan/p/5620209.html

    解法二: 可以使用二分查找做,不过应该没有利用矩阵的特点来做速度快。

  • 相关阅读:
    C++中的ravalue学习笔记
    C++中的抽象类
    C++中的显式类型转换
    C++中的继承和多继承
    C++中的多态
    Yocto学习笔记
    HIDL学习笔记
    hadoop2.5搭建过程
    《Redis设计与实现》学习笔记
    40 数组中只出现一次的数字
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5622395.html
Copyright © 2011-2022 走看看