zoukankan      html  css  js  c++  java
  • leetcode 74. 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.
    

    我的想法是2次二分,先找target所在的行,再找所在的列。

    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            int n = matrix.size();
            if (n == 0) return false;
            int m = matrix[0].size();
            if (m == 0) return false;
            vector<int> v;
            for (int i = 0; i < matrix.size(); ++i) {
                v.push_back(matrix[i][0]);
                v.push_back(matrix[i][m-1]);
            }
            int id = lower_bound(v.begin(), v.end(), target) - v.begin();
            //cout << id << endl;
            if (id >= v.size()) return false;
            if (v[id] == target) return  true;
            if (id == 0) return false;
            int t;
            if (id & 1) t = id / 2;
            else t = (id - 1) / 2;
            int x = lower_bound(matrix[t].begin(), matrix[t].end(),target) - matrix[t].begin();
            if (x >= m) return false;
            return matrix[t][x] == target;
        }
    };
    
  • 相关阅读:
    深入理解 Netty-新连接接入
    深入理解 Netty-Channel架构体系
    深入理解 NioEventLoop启动流程
    深入理解 NioEventLoopGroup初始化
    java8-Stream
    WebSocket+Netty构建web聊天程序
    Jpa 笔记
    观察者模式
    一只垂直的小爬虫
    字符集编码全方位解析
  • 原文地址:https://www.cnblogs.com/pk28/p/7650124.html
Copyright © 2011-2022 走看看