本文主要是介绍[LeetCode]240.Search a 2D Matrix II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following 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]
]
Given target = 5, return true.
Given target = 20, return false.
思路
杨氏矩阵
代码
/*---------------------------------------
* 日期:2015-08-01
* 作者:SJF0115
* 题目: 240.Search a 2D Matrix II
* 网址:https://leetcode.com/problems/search-a-2d-matrix-ii/
* 结果:AC
* 来源:LeetCode
* 博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;class Solution {
public:bool searchMatrix(vector<vector<int>>& matrix, int target) {if(matrix.empty()){return false;}//ifint row = matrix.size();int col = matrix[0].size();int x = 0,y = col - 1;// 杨氏矩阵解法从右上角元素开始while(x < row && y >= 0){if(matrix[x][y] == target){return true;}//ifelse if(matrix[x][y] < target){++x;}//elseelse{--y;}}//whilereturn false;}
};int main(){Solution s;int target = 20;vector<vector<int> > 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}};bool result = s.searchMatrix(matrix,target);// 输出cout<<result<<endl;return 0;
}
这篇关于[LeetCode]240.Search a 2D Matrix II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!