搜索二维矩阵 II

搜索二维矩阵 II

作者: Turbo

时间限制: 1s

章节: 二分查找

问题描述

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。要求使用二分查找。

该矩阵具有以下特性:

每行的元素从左到右升序排列。

每列的元素从上到下升序排列。

说明:以上所说的升序,由于中间存在重复元素,因此严格来说,"升序"应该理解成"非递减"

示例:

现有矩阵 matrix 如下:

\[1, 4, 7, 11, 15\], \[2, 5, 8, 12, 19\], \[3, 6, 9, 16, 22\], \[10, 13, 14, 17, 24\], \[18, 21, 23, 26, 30

]

给定 target = 5,返回 true。

给定 target = 20,返回 false。

可使用以下main函数:

int main()

{

vector<vector<int> > matrix;

int target;

int m,n,e;

cin>>m;

cin>>n;

for(int i=0; i<m; i++)

{

vector<int> aRow;

for(int j=0; j<n; j++)

{

cin>>e;

aRow.push_back(e);

}

matrix.push_back(aRow);

}

cin>>target;

bool res=Solution().searchMatrix(matrix,target);

cout<<(res?"true":"false")<<endl;

return 0;

}

5 5

1 4 7 11 15

2 5 8 12 19

3 6 9 16 22

10 13 14 17 24

18 21 23 26 30

5

true

从右上角 (0, n-1) 出发,规则是:

  • 如果 当前值 > target → 向左走(col--

  • 如果 当前值 < target → 向下走(row++

  • 如果相等 → 返回 true

最坏情况下 ,你最多向左走 n-1 步,向下走 m-1 步,加起来就是 (m-1) + (n-1) = m + n - 2 步。

所以时间复杂度是 O(m + n),这是线性复杂度,不是对数复杂度。

cpp 复制代码
# include<bits/stdc++.h>
using namespace std;
class Solution{
	public:
		bool searchMatrix(vector<vector<int> >& v,int target){
			int m = v.size();
			if(m==0) return 0;
			int n = v[0].size();
			int i = 0;
			int j = n - 1;
			while(i<m&&j>=0){
				if(v[i][j]==target) return true;
				if(target>v[i][j]) i++;
				else j--;
			}
			return false;
		}
};
int main()

{

    vector<vector<int> > matrix;

    int target;

    int m,n,e;

    cin>>m;

    cin>>n;

    for(int i=0; i<m; i++)

    {

        vector<int> aRow;

        for(int j=0; j<n; j++)

        {

            cin>>e;

            aRow.push_back(e);

        }

        matrix.push_back(aRow);

    }

    cin>>target;

    bool res=Solution().searchMatrix(matrix,target);

    cout<<(res?"true":"false")<<endl;

    return 0;

}
相关推荐
allnlei17 小时前
s6-overlay - 装在 Docker 容器里的轻量级管家
java·docker·容器
wzdark21 小时前
基于堆的优先队列实现原理与复杂度分析4
算法
彧azz1 天前
图的存储结构详解:邻接矩阵的原理、实现与应用
开发语言·数据结构·学习·php
IT_Octopus1 天前
IntelliJ 本地日志路径自定义:`-DLOG_PATH=./logs` 为什么总“不听话“
java·log4j·intellij-idea
老王熬夜敲代码1 天前
BLAKE3:最快的密码学哈希函数
算法·密码学·哈希算法
hansang_IR1 天前
【题解】P4460 [CQOI2018] 解锁屏幕
c++·算法
见闻小天地1 天前
简博斯JG-C系列彩色激光同轴位移计:摄像头模组对位与行程测量的技术价值观察
人工智能·算法
长征coder1 天前
【无标题】
java·性能优化
新时代牛马1 天前
PCI与PCIe 硬件原理、配置空间/BAR 与 Linux 驱动完整篇:从 LTSSM、TLP 到 ECAM 与probe
java·linux·服务器
葫三生1 天前
《论三生原理》神话学构想与“神话历史”理论、《古史中的神话》思路异同?
大数据·人工智能·科技·深度学习·算法