搜索二维矩阵 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;

}
相关推荐
小星星闪亮登场11 分钟前
2026萌新联赛第三场-- (郑州轻工业大学)
数据结构·c++·经验分享·算法·贪心算法·排序算法·深度优先
wgego21 分钟前
基础的反序列化一些总结(php和java)
java·开发语言·笔记
冻柠檬飞冰走茶33 分钟前
PTA基础编程题目集 7-8超速判断(C++语言实现)
开发语言·数据结构·c++·算法
机建狂魔1 小时前
Codex 接入第三方模型 API 实战:以 Mimo 为例
java·服务器·数据库·ai·ai编程·codex
玖玥拾1 小时前
LeetCode 88 合并两个有序数组
算法·leetcode
数据皮皮侠AI1 小时前
上市公司数字供应链金融指数(2010-2024)
大数据·人工智能·算法
2501_942389551 小时前
Epoch AI旗下FrontierMath的负责人Elliot Glazer
数据结构·决策树·动态规划·散列表
山峰哥1 小时前
数据库工程与SQL调优:从慢查询到秒级响应的实战之路
java·开发语言·数据库·sql·深度优先·启发式算法
乐观的Terry2 小时前
11、发布系统-用户认证与权限体系
java·spring boot·spring·spring cloud·mybatis
前端开发张小七2 小时前
Java 学习笔记 · 第二课:面向对象核心(封装、继承、多态)及接口与异常
java·后端·程序员