[LeetCode74]Search a 2D Matrix

本文介绍了一种在具有特定排列规则的二维矩阵中高效查找目标值的算法,利用矩阵的有序特性,实现时间复杂度为O(n)的快速搜索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目来源:https://leetcode.com/problems/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.

题目翻译: 给定一个矩阵和一个特定值, 要求写出一个高效的算法在这个矩阵中快速的找出是否这个给定的
值存在. 但是这个矩阵有以下特征.
    1. 对于每一行, 数值是从左到右从小到大排列的.
    2. 对于每一列, 数值是从上到下从小到大排列的.
题目解析: 对于这个给定的矩阵, 我们如果用brute force蛮力解法, 用两个嵌套循环, O(n^2)便可以得到答案.但
是我们需要注意的是这道题已经给定了这个矩阵的两个特性, 这两个特性对于提高我们算法的时间复杂度
有很大帮助, 首先我们给出一个O(n)的解法, 也就是说我们可以固定住右上角或者左下角的元素, 根据递增或者递减
的规律, 我们可以判断这个给定的数值是否存在于这个矩阵当中.


class Solution74{
public:
	bool searchMatrix(vector<vector<int>> &matrix, int target){
		/*
		数组为0,return false
		*/
		if (matrix.size() == 0){
			return false;
		}
		if (matrix[0].size() == 0){
			return false;
		}
		int row = matrix.size()-1;
		int col = 0;
		while (row >= 0 && col < matrix[0].size()){
			if (target < matrix[row][col]){
				--row;
			}
			else if (target > matrix[row][col]){
				++col;
			}
			else
				return true;
		}
		return false;
	}
};


int main()
{
	Solution74 solution;
	{
		vector < vector < int > > vec = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } };
		int target = 21;
		if (solution.searchMatrix(vec, target)){
			cout << "true" << endl;
		}
		else
		{
			cout << "false";
		}
	}
	system("pause");
	return 0;
}













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值