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

    https://leetcode.com/problems/search-a-2d-matrix/#/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.

    考点只有一个:2D array 降维成 1D array index trick. 

    public boolean searchMatrix(int[][] matrix, int target) {
            // write your code here
            if (matrix.length == 0) {
                return false;
            }
            if (matrix[0].length == 0) {
                return false;
            }
            
            int n = matrix.length;
            int m = matrix[0].length;
            int low = 0, high = m * n - 1;
            
            while (low + 1 < high) {
                int mid = low + (high - low) / 2;
                int x = mid / m, y = mid % m;
                if (matrix[x][y] == target){
                    return true;
                } else if (matrix[x][y] > target){
                    high = mid;
                } else {
                    low = mid;
                }
            }
            
            if (matrix[low / m][low % m] == target 
                || matrix[high / m][high % m] == target) {
                return true;
            }
            return false;
        }
    

      

  • 相关阅读:
    python元编程(metaclass)
    STL源码剖析:序
    高效C++:定制new和delete
    高效C++:模板和泛型编程
    高效C++:继承和实现
    高效C++:实现
    高效C++:设计与声明
    高效C++:资源管理
    高效C++:构造/析构/赋值
    Noip2017退役记
  • 原文地址:https://www.cnblogs.com/apanda009/p/7092993.html
Copyright © 2011-2022 走看看