240. Search a 2D Matrix II 题解
来源:互联网 发布:中国电信2g网络制式 编辑:程序博客网 时间:2024/05/18 06:25
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
.
题目链接:240. Search a 2D Matrix II
算法描述:
由题意知,给定一个二维矩阵,该二维矩阵每行元素从左到右递增排列,每列元素从上到下递增排列。我们需要在这个矩阵中找到一个目标值 “target” ,且运用复杂度小的搜索算法。
我们不能按照简单的遍历算法来做,可以按照这样的思路:在矩阵中找到一个合理的“中间”位置,这个“中间”位置可以很方便的在矩阵中遍历到其它元素,这个“中间”位置即矩阵的右上角位置,我们比较这个值与目标值 “target” 的大小关系,当目标值 “target” 大于这个位置的值,由于矩阵中元素的排列关系,我们只能继续向下查找。当目标值 “target” 小于这个位置的值时,我们向左查找。可以想象,查找的路线为 “阶梯形” 。
如果查找的位置超过矩阵的边界,则返回 false。
代码:
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.size() == 0 || matrix[0].size() == 0){ return false; } int i = 0; int j = matrix[0].size()-1; while(i<matrix.size() && j>=0){ if(matrix[i][j] == target){ return true; } else if(matrix[i][j] > target){ j--; } else{ i++; } } return false; }};
0 0
- leetcode题解-74. Search a 2D Matrix && 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II 题解
- LeetCode 题解(149): Search a 2D Matrix II
- LeetCode240. Search a 2D Matrix II题解
- Lintcode38 Search a 2D Matrix II solution 题解
- LeetCode240. Search a 2D Matrix II题解
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- Leetcode 231 and 342. Power of 2, Power of 4
- 使用codematic开发一个畅想汇项目,结课作业
- 树莓派简介与应用
- 物理地址
- PAT_1044. Shopping in Mars
- 240. Search a 2D Matrix II 题解
- 【BZOJ2463】 [中山市选2009]谁能赢呢?
- 蓝桥杯 历届试题 高僧斗法 (stairNim博弈)
- 通过ID获取元素
- 堆和栈
- linux shell:[0] &&和||使用方法
- GeoServer安装遇到的问题
- apue第八章 进程控制(2)
- linux3.0-内核自带led驱动移植