zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    解题思路:

    二分,递归。

    class Solution {
    public:
        int m = 0, n = 0;
        vector<vector<int>> data;
        bool search(int left, int right, int target)
        {
            int mid = (right + left) / 2;
            if(right - left == 1) return target == data[left / n][left % n];
            else return search(left, mid, target) || search(mid, right, target);
        }
        bool searchMatrix(vector<vector<int> > &matrix, int target) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(matrix.size() == 0) return false;
            data = matrix;
            m = matrix.size(), n = matrix[0].size();
            return search(0, m * n, target);
        }
    };
  • 相关阅读:
    对MVC模式与MVVM模式的认识
    优雅降级和渐进增强
    入园第一天
    看看AQS阻塞队列和条件队列
    简单看看LockSupport和AQS
    简单看看LongAccumulator
    JUC中的原子操作类及其原理
    java并发基础知识
    简单看看es6解构赋值
    简单使用vue-cli
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3419273.html
Copyright © 2011-2022 走看看