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.

    什么叫丧心病狂?m+n已经不能满足人类的欲望了,如果用二路二分,效率可达O(log m + log n)

    我就不丧心病狂了。

    class Solution {
    public:
        bool searchMatrix(vector<vector<int> > &matrix, int target) {
            
            int x = matrix.size();
            int y = matrix[0].size();
            if(x==0)return false;
            
            int i;
            for(i = 0 ; i < x-1 ;i++)
            if(matrix[i+1][0] > target)break;
            else if(matrix[i+1][0] == target)return 1;
            
            if(matrix[x-1][0] < target) i = x-1;
            if(matrix[x-1][0] == target) return 1;
            
            int j = 0;
            for( j = 0 ; j < y-1 ;j++)
            if(matrix[i][j] == target)return 1;
            else if(matrix[i][j+1] > target)break;
            
            if(matrix[i][j]  == target)return 1;
            return 0;
            
            
        }
    };
    

      

  • 相关阅读:
    初始化和实例化对象
    java设计模式
    构造方法的访问级别
    C#连接操作sqlite
    using三种用法
    C#获取当前日期时间
    C#生成excel到其他电脑生成报表时报错
    [Python] VSCode隐藏__pycache__文件夹
    [Git] 常用操作速查
    [Pytorch] 卷积尺寸计算
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3599217.html
Copyright © 2011-2022 走看看