LeetCode | Search a 2D Matrix
来源:互联网 发布:transmac制作mac安装盘 编辑:程序博客网 时间:2024/06/06 18:03
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.
从一个二维数组里面寻找元素。
解决思路是从左下角开始寻找,因为数组的排列方式使得我们从左下角出发的话,比它大的位于右侧,比他小的位于上侧。
于是就可以利用这么一个递归的过程【事实上也可以写成非常简单的非递归】从而正确地找到该数字是否在这个矩阵里面。
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m=matrix.size(); int n=matrix[0].size(); return searchTarget(matrix,target,m-1,0); } bool searchTarget(vector<vector<int>>& matrix, int target,int x,int y) { int m=matrix.size(); int n=matrix[0].size(); if(x<0 || x>=m || y<0 || y>=n) return false; if(target==matrix[x][y]) return true; if(target < matrix[x][y]) return searchTarget(matrix,target,x-1,y); else return searchTarget(matrix,target,x,y+1); }};
0 0
- [leetcode][Search] Search a 2D Matrix
- LeetCode: Search a 2D Matrix
- LeetCode Search a 2D Matrix
- [Leetcode] Search a 2D Matrix
- LeetCode : Search a 2D Matrix
- [LeetCode] Search a 2D Matrix
- Leetcode 74 Search a 2D Matrix
- leetcode 90: Search a 2D Matrix
- [LeetCode]Search a 2D Matrix
- [Leetcode] Search a 2-D matrix
- [Leetcode]Search a 2D Matrix
- [leetcode]Search a 2D Matrix
- LeetCode-Search a 2D Matrix
- [leetcode] Search a 2D Matrix
- LeetCode - Search a 2D Matrix
- LeetCode:Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- leetcode之Search a 2D Matrix
- 16 暑期校训 DAY6
- Java生成验证码
- 使用Category标签隐藏Jekyll博客文章
- Linux 终端生存指南
- debian8.5下Cinnamon桌面Bug#2解决方法
- LeetCode | Search a 2D Matrix
- iOS UI: UIMenuController | InputView 折腾记
- MySQL DBA 面试题目 答疑记 《01》
- Java中接口与实例化【引用】
- 【杭电oj2012】素数判定
- HDU 5811 (拓扑排序 LIS)
- “懒惰”Linux 管理员的 10 个关键技巧
- 【杭电oj2013】蟠桃记
- Lua入门教程