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;
        }
    };
  • 相关阅读:
    zookeeper项目使用几点小结
    Dubbo架构设计详解
    关于web.xml不同版本之间的区别
    bat定时执行,清除PHP缓存
    新闻列表标题省略样式
    php把时间格式化
    HTML5中的拖放
    Redis JAVA客户端 Jedis常用方法
    Redis 简介
    SpringBoot DataSource 配置说明
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854625.html
Copyright © 2011-2022 走看看