zoukankan      html  css  js  c++  java
  • 【leetcode】74. 搜索二维矩阵

    题目链接:传送门

     

    题目描述

      编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

      每行中的整数从左到右按升序排列。

      每行的第一个整数大于前一行的最后一个整数。



    示例 1:

    输入:

    matrix = [
      [1, 3, 5, 7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
     ]
    target = 3

    输出: true


    示例2:

    输入:
    matrix = [
      [1, 3, 5, 7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    target = 13

    输出:

    false


    【题解】:

      写题解的原因在于,我不知道二维数组的处理方法,应该利用元素的行列坐标来找出相应的序号,然后对于序号来进行二分排序,找出对应的值。

    【代码】:

     1 class Solution {
     2 public:
     3     bool searchMatrix(vector<vector<int>>& matrix, int target) {
     4         if (matrix.empty() || matrix[0].empty()) return false;
     5         int n = matrix.size() , m = matrix[0].size() ; 
     6         int L = 0 , R = n * m - 1 ,Mid , ans = 0 ;
     7         while ( L<=R ){
     8             Mid = ( L+R ) >> 1 ;
     9             if ( matrix[Mid/m][Mid%m] >= target ){
    10                 ans = Mid ; 
    11                 R = Mid - 1; 
    12             }else{
    13                 L = Mid + 1 ;
    14             }
    15         }
    16         return matrix[ans/m][ans%m] == target ; 
    17     }
    18 };
    搜索二维矩阵
  • 相关阅读:
    基于s5pv210的uboot总结
    QQ群笔记
    设计模式----适配器模式
    设计模式----桥接模式
    设计模式----建造者模式
    设计模式----原型模式
    设计模式----单例模式
    设计模式----工厂方法模式
    设计模式----设计原则
    JUnit单元测试--小试牛刀
  • 原文地址:https://www.cnblogs.com/Osea/p/11182191.html
Copyright © 2011-2022 走看看