zoukankan      html  css  js  c++  java
  • [LeetCode] Search a 2D Matrix

    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:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            //二分查找,将矩阵查找转化成线性查找
            int m = matrix.size();
            if(m==0){
                return false;
            }
            int n = matrix[0].size();
            if(n==0){
                return false;
            }
            int start = 0, end = m*n-1;
            while(start<=end){
                int middle = (start + end)/2;
                int x = middle / n;
                int y = middle % n;
                if(matrix[x][y]==target){
                    return true;
                }else if(matrix[x][y]<target){
                    start = middle + 1;
                }else{
                    end = middle - 1;
                }
            }
            return false;
        }
    };


  • 相关阅读:
    八、springboot 简单优雅的通过docker-compose 构建
    【并发编程】ThreadLocal其实很简单
    计算机网络
    相似度
    不同激活函数的区别
    快速排序+归并排序
    xgboost
    c++面试
    PCA算法和SVD
    各种排序算法的时间复杂度和空间复杂度
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/6897068.html
Copyright © 2011-2022 走看看