[LeetCode]240.Search a 2D Matrix II
来源:互联网 发布:mac邮件设置qq邮箱 编辑:程序博客网 时间:2024/06/03 02:07
题目
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; }//if int 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; }//if else if(matrix[x][y] < target){ ++x; }//else else{ --y; } }//while return 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;}
1 0
- #leetcode#Search a 2D Matrix II
- [LeetCode] Search a 2D Matrix II
- leetcode: Search a 2D Matrix II
- leetcode - Search a 2D Matrix II
- [leetcode] Search a 2D Matrix II
- 【leetcode】Search a 2D Matrix II
- Leetcode: Search a 2D Matrix II
- LeetCode Search a 2D Matrix II
- [Leetcode]Search a 2D Matrix II
- [LeetCode]Search a 2D Matrix II
- LeetCode Search a 2D Matrix II
- [LeetCode]Search a 2D Matrix II
- LeetCode || Search a 2D Matrix II
- LeetCode----Search a 2D Matrix II
- Leetcode: Search a 2D Matrix II
- *LeetCode-Search a 2D Matrix II
- Search a 2D Matrix II -- leetcode
- leetcode | Search a 2D Matrix II
- google code jam 2009 round1 c
- php学习笔记_5_数组及预定义变量(未完)
- bitset 基本使用
- Tomcat6 一些调优设置内存和连接数
- uva10305(拓扑
- [LeetCode]240.Search a 2D Matrix II
- Problem F
- Redis 数据持久化
- 高效Linux之Terminal下实用快捷键
- 07 JAVA IO流
- Lucene八(搜索分页)
- 数据结构 线性表的顺序存储
- 数据库设计--实体关系图(ERD)
- ExpandableListView组件学习笔记