zoukankan      html  css  js  c++  java
  • 74. Search a 2D Matrix (Graph; Divide-and-Conquer)

    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:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            int start = 0, end = matrix.size()-1;
            int mid;
            int lineNum;
            while(start<=end){
                mid = start + ((end-start)>>1);
                if(matrix[mid][0]<target){
                    start = mid+1;
                }
                else if(matrix[mid][0]>target){
                    end = mid-1;
                }
                else return true;
            }
            if(end < 0) return false;
            lineNum = end;
            start = 0;
            end = matrix[0].size()-1;
            while(start<=end){
                mid = start + ((end-start)>>1);
                
                if(matrix[lineNum][mid]<target){
                    start = mid+1;
                }
                else if(matrix[lineNum][mid]>target){
                    end = mid-1;
                    
                }
                else return true;
            }
            return false;
        }
    };
  • 相关阅读:
    readonly
    怎么查看ubuntu是32bit还是64bit的?
    array_diff使用注意
    PhpStorm 快速查找文件 `Ctrl`+`Shift`+`N`
    discuz安装,uc_server目录下乱码问题:
    vim,删除所有
    查看文件大小
    代码调试小结(一)
    Ansible 远程执行脚本
    Ansible 拷贝文件或目录
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854625.html
Copyright © 2011-2022 走看看